我是python新手,正在尝试学习一些新模块。不管是幸运还是不幸,我选择了urllib2模块,并开始使用它来处理一个给我带来问题的URL。在
首先,我创建了Request对象,然后对response对象调用Read()。它失败了。结果它被重定向了,但错误代码仍然是200。不知道发生了什么事。这是密码--def get_url_data(url):
print "Getting URL " + url
user_agent = "Mozilla/5.0 (Windows NT 6.0; rv:14.0) Gecko/20100101 Firefox/14.0.1"
headers = { 'User-Agent' : user_agent }
request = urllib2.Request(url, str(headers) )
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
print response.geturl()
print response.info()
print response.getcode()
return False;
else:
print response
print response.info()
print response.getcode()
print response.geturl()
return response
我原以为会收到301、302或303,但我看到的是200。这是我看到的反应——
^{pr2}$
有人能解释一下这个URL是什么以及如何处理它吗?我知道我可以使用“处理重定向”部分Diveintopython.net但是在那页上我也看到了同样的回复200。在
编辑:使用DiveintoPython的代码,我看到它是一个临时重定向。我不明白为什么代码中的HTTP错误代码是200。这不应该是实际的返回码吗?在
现在我看得更清楚了,它一点也不奇怪。我正在编辑标题。在
EDIT3:如果urllib2自动遵循重定向,我不确定为什么下面的代码没有得到辣椒网. 在docObj = get_url_data(url)
doc = docObj.read()
soup = BeautifulSoup(doc, 'lxml')
print(soup.prettify())