我建议不要在任何现代 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:
要了解如何集成免费的 Postal Service® Address 和
将 API 跟踪到您的应用程序中,请访问
www.usps.com/webtools。
也足够公平。我建议去那里注册。如果有适当的方法,就没有必要抓取 HTML。
但是,如果您真的想通过代码提取原始 HTML:首先通过 Curl 让它工作。
调出 Chrome 开发者工具并重新加载页面。右键单击并查找“复制为 CURL”。您可以编辑链接。以下对我有用,尽管它可能会被修剪得更多:
curl 'https://tools.usps.com/go/TrackConfirmAction.action?tRef=fullpage&tLc=1&text28777=&tLabels=LN594080445CN\]' \
-H 'Accept-Encoding: gzip, deflate, sdch' \
-H 'Accept-Language: en-US,en;q=0.8' \
-H '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' \
-H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' \
--compressed
这可以修剪。下面的代码适用于漂亮的requests 模块:
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。