python-3.x - 使用 urllib.request 查询具有一系列 x-api-key header 的 url

标签 python-3.x http-headers urllib

我得到了一个 url/端口,必须使用 python 3.8 从服务器获取响应。 “服务器”需要一个“x-api-key”作为密码,没有正确的 key 将不会显示信息。 (至少这是我从中得到的)

key 应该在 5500 和 5600 之间。 我是 python 的新手,想知道为什么我的代码没有返回任何内容。 我使用标题错误吗? 我已经尝试了好几个小时/谷歌搜索了几个小时。

# Alien Signal API listening on http://127.0.0.1:8082
# Use HTTP GET with x-api-key header to get signal
# We have narrowed down the key to be in the range of 5500 to 5600
# Note: The script can timeout if this occurs try narrowing
# down your search
#
import urllib.parse
import urllib.request

url = "http://127.0.0.1:8082"
startingKey = 5500
endingKey = 5600
hdr = {}

while startingKey <= endingKey:
    hdr = { 'x-api-key' : str(startingKey) }
    req = urllib.request.Request(url, headers=hdr)
    response = urllib.request.urlopen(req)
    response.read()
    startingKey = startingKey + 1

最佳答案

虽然您大部分都答对了,但您忘记打印了。只需添加这行代码而不是“response.read()”:

print(response.read())

或者你可以这样做:

html = response.read()
print(html)

关于python-3.x - 使用 urllib.request 查询具有一系列 x-api-key header 的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65373393/

相关文章:

python - 打印到 CSV 会导致每个字符之间有一个空格?

java - 如何使用 RestTemplate 传递 header ?

http-headers - Chrome 网络检查器中缺少请求 header (和发送的 cookie)?

python 3,错误处理urllib请求

python-3.x - 使用 ReportLab 有条件地为表格单元格着色

python - 减去保留 "None"元素的两个列表

python - 如何注释可以转换为 bool 值的参数?

c# - HttpWebRequest.Headers.Add ("Cookie",值)与 HttpWebRequest.CookieContainer

Python urllib.urlopen() 调用不适用于浏览器接受的 URL

python - 引发运行时错误 ('FPDF error: ' +msg) 运行时错误 : FPDF error: Unsupported image type: chapter_1_romance_dawn