Python 从维基百科中随机抽取页面时,脚本总是得到302响应
我可以从维基百科上用Python 从维基百科中随机抽取页面时,脚本总是得到302响应,python,http,wikipedia,Python,Http,Wikipedia,我可以从维基百科上用 import httplib conn = httplib.HTTPConnection("en.wikipedia.org") conn.debuglevel = 1 conn.request("GET","/wiki/Normal_Distribution",headers={'User-Agent':'Python httplib'}) r1 = conn.getresponse() r1.read() 正常的反应是 reply: 'HTTP/1.0 200 OK\
import httplib
conn = httplib.HTTPConnection("en.wikipedia.org")
conn.debuglevel = 1
conn.request("GET","/wiki/Normal_Distribution",headers={'User-Agent':'Python httplib'})
r1 = conn.getresponse()
r1.read()
正常的反应是
reply: 'HTTP/1.0 200 OK\r\n'
header: Date: Sun, 03 Apr 2011 23:49:36 GMT
header: Server: Apache
header: Cache-Control: private, s-maxage=0, max-age=0, must-revalidate
header: Content-Language: en
header: Vary: Accept-Encoding,Cookie
header: Last-Modified: Sun, 03 Apr 2011 17:23:50 GMT
header: Content-Length: 263638
header: Content-Type: text/html; charset=UTF-8
header: Age: 1280309
header: X-Cache: HIT from sq77.wikimedia.org
header: X-Cache-Lookup: HIT from sq77.wikimedia.org:3128
header: X-Cache: MISS from sq66.wikimedia.org
header: X-Cache-Lookup: MISS from sq66.wikimedia.org:80
header: Connection: close
但如果我尝试使用/wiki/Special:random拉取一个随机页面,我会得到302响应和一个空页面
reply: 'HTTP/1.0 302 Moved Temporarily\r\n'
header: Date: Mon, 18 Apr 2011 19:25:52 GMT
header: Server: Apache
header: Cache-Control: private, s-maxage=0, max-age=0, must-revalidate
header: Vary: Accept-Encoding,Cookie
header: Expires: Thu, 01 Jan 1970 00:00:00 GMT
header: Location: http://en.wikipedia.org/wiki/Tuticorin_Port_Trust
header: Content-Length: 0
header: Content-Type: text/html; charset=utf-8
header: X-Cache: MISS from sq60.wikimedia.org
header: X-Cache-Lookup: MISS from sq60.wikimedia.org:3128
header: X-Cache: MISS from sq62.wikimedia.org
header: X-Cache-Lookup: MISS from sq62.wikimedia.org:80
header: Connection: close
如何获取非空的随机页面?HTTP代码302表示您正在被重定向。如果您查看位置标题,您将看到应该在哪里提出新请求。然后你可以向那个URL发出请求,你希望在那个页面上得到200分
澄清:您被要求在其他地方重试请求。这就是为什么客户机在收到302时需要发出另一个请求。维基百科的随机页面显然是通过在其数据库中选择一个随机页面,然后返回302响应,新页面作为位置字段。如果您查看其他302响应,我相信您会在位置字段中看到不同的页面。302是一个重定向。它告诉你下一行的方向:
header: Location: http://en.wikipedia.org/wiki/tuticorin_port_trust
您只需按照重定向操作即可。查看位置标题: 标题:位置:
它说你应该重定向到那个页面。读取该标题并对该页面执行另一个请求。重定向时,响应对象的代码将为302,并且
geturl()
方法将报告重定向URL。Python的标准HTTP库使得在默认情况下处理重定向非常重要。帮你自己一个忙,不要麻烦这些东西,使用第三方库,它是urllib2
的替代品
使用mechanize,您的代码如下所示:
import httplib
import mechanize
host = 'en.wikipedia.org'
path = '/wiki/Special:Random'
url = 'http://' + host + path # We have to pass a http:// url
# It still uses httplib.HTTPConnection, so we can debug
httplib.HTTPConnection.debuglevel = 1
request = mechanize.Request(url, headers={'User-Agent': 'Python-mechanize'})
response = mechanize.urlopen(request)
print response.code
# => 200
print response.geturl()
# => 'http://en.wikipedia.org/wiki/Faliszowice,_Lesser_Poland_Voivodeship'
data = response.read()