使用urllib urlopen read函数,但get non

2024-09-29 01:33:18 发布

您现在位置:Python中文网/ 问答频道 /正文

[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()

但是得到佩奇

我的版本:2.7.6在


Tags: httpscomurlgoactionurllibtoolstlc
3条回答

嗯,我尝试使用python包requests,但首先有一个错误: requests.exceptions.TooManyRedirects: Exceeded 30 redirects。在

它似乎从url重定向到另一个并像这样循环。也许它用urllib失败了。 我还检查了urlopen的doc,似乎对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

创建会话修复了关于最大重定向错误的错误。更多信息请参见this question。 在response.text中,你有所有的代码页,我猜是你想要的。在

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

我建议不要在任何现代Python上下文中使用urllib。使用“Requests”(“HTTP for Humans”)代替。在

但在此之前,正如@Skyler所说,结果是重定向,您的第一站应该是查看curl报告的内容:

$ curl -I 'https://tools.usps.com/go/TrackConfirmAction.action?tRef=fullpage&tLc=1&text28777=&tLabels=LN594080445CN\]'
HTTP/1.1 301 Moved Permanently
Server: AkamaiGHost
Content-Length: 0
Location: https://www.usps.com/root/global/server_responses/webtools-msg.htm
Date: Wed, 31 Dec 2014 10:43:14 GMT
Connection: keep-alive

没什么大不了的,但是你可以看到URL it redirects to states

To learn about integrating the free Postal Service® Address and Tracking API's into your application, please visit www.usps.com/webtools.

也很公平。我建议去那里报名。如果有一个合适的方法,就没有必要抓取HTML。在

但是,如果真的想通过代码获取原始HTML:首先通过Curl让它工作。在

打开Chrome开发工具并重新加载页面。右键单击并查找“复制为卷曲”。您可以编辑链接。以下是我的工作,虽然它可能会被削减更多:

^{pr2}$

这个可以修剪。下面的代码与nicerequests模块一起工作:

import requests

headers = {
    'Accept-Language': 'en-US,en;q=0.8',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
}
r = requests.get('https://tools.usps.com/go/TrackConfirmAction.action?tRef=fullpage&tLc=1&text28777=&tLabels=LN594080445CN]', headers=headers)

print "Status: %s" % r.status_code
print "Content-type: %s" % r.headers['content-type']
print "Content length: %d" % len(r.text)

运行中:

$ python demo.py
Status: 200
Content-type: text/html
Content length: 55142

更干净:

params = {
    'tRef': 'fullpage',
    'tLc': '1',
    'text28777': '',
    'tLabels': 'LN594080445CN]',
}

r = requests.get('https://tools.usps.com/go/TrackConfirmAction.action',
        params=params,
        headers=headers)

正如我所说,我认为这不是正确的选择。使用USPS API。在

我尝试了这个URL,发现错误是由HTTP错误301引起的。应该是这个网站的防蜘蛛机制造成的。您必须设计一个复杂的用户代理来获取页面,而不仅仅是一个简单的urlopen。在

相关问题 更多 >