python - 使用 urllib urlopen 读取函数但没有得到任何结果

标签 python urlopen

[https://tools.usps.com/go/TrackConfirmAction.action?tRef=fullpage&tLc=1&text28777=&tLabels=LN594080445CN]

import urllib
url='https://tools.usps.com/go/TrackConfirmAction.action?tRef=fullpage&tLc=1&text28777=&tLabels=LN594080445CN'  
page=urllib.urlopen(url).read()

但是获取page=''

我的版本:2.7.6

最佳答案

嗯,我尝试使用 python 包 requests首先有一个错误: requests.exceptions.TooManyRedirects:超过 30 个重定向

它似乎从网址重定向到另一个网址并像这样循环。也许 urllib 失败了。 我还检查了 urlopen 的文档,似乎 https 请求有一些问题。

无论我发现这段代码可以解决您的问题:

import requests

url='https://tools.usps.com/go/TrackConfirmAction.action?tRef=fullpage&tLc=1&text28777=&tLabels=LN594080445CN'

s = requests.session()
s.headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'

response = s.get(url)
print response.text

创建 session 修复有关最大重定向错误的错误。更多信息请参见this question 。 在 response.text 中,您拥有所有代码页,我猜这就是您想要的。

当然,您需要添加您的特定用户代理。例如,有我的,但你的可能不同。可以找到here 希望有帮助!

关于python - 使用 urllib urlopen 读取函数但没有得到任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27719476/

相关文章:

python-3.x - Python 3.6 urllib 为什么行以 b 开头

python - 尝试下载 gzip 文件时出现 urlopen 问题

beautifulsoup - 使用 python 登录网站

javascript - 如何在 JavaScript 中使用 $.getJSON 检索 python 文件数据?

Python 检查网站是否存在

python - 超时后 urlopen 调用不会在超时后终止

python - 使用scrapy从脚本标签中提取数据

python - 如何修复 TypeError : 'file' object is unsubscriptable

python - 测量外部程序使用的耗时、内存量和 CPU

python - 使用 rml 更改 openerp 7 页眉/页脚