【发布时间】:2012-06-11 22:57:02
【问题描述】:
我在使用 python 访问网页时遇到问题——它抛出 HTTP 错误 403。在浏览堆栈溢出后,我发现许多其他用户遇到了相同的错误,并通过更改请求的标头来解决它。我试过了,但仍然收到错误。
这是我的代码:
req = urllib2.Request("http://www.mozilla.org")
req.add_header('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8a3) Gecko/20040817')
try:
response = urllib2.urlopen(req)
except urllib2.URLError, (err):
print "URL error(%s)" % (err)
编辑:这是我的一大段代码,它是网络爬虫的开始。另外——我一直使用http://www.mozilla.org 作为我的测试网址,尽管它似乎不适用于任何其他网址,例如 google 和 yahoo。
#!/usr/bin/python
import sys
import urllib2
import urlparse
tocrawl = set([sys.argv[1]])
crawled = set([])
while 1:
try:
crawling = tocrawl.pop()
print 'Crawling: ', crawling
except KeyError:
print 'No more to crawl!'
raise StopIteration
url = urlparse.urlparse(crawling)
print 'Url parse returned ', url
req = urllib2.Request(crawling)
req.add_header('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8a3) Gecko/20040817')
print 'header: ', req.get_header('User-agent')
try:
print 'test'
response = urllib2.urlopen(req)
print 'test2'
print 'response: ', response
except urllib2.URLError, (err):
print "URL error(%s)" % (err)
continue
msg = response.read()
【问题讨论】:
-
你真的要获取mozilla.org吗?因为你的代码对我来说很好。如果没有,如果没有您尝试获取的 URL,就很难具体说明。
-
我无法重现您的结果。你能分享更多可能导致问题的代码吗?响应正文中是否还有错误消息?
标签: python http http-status-code-403