用Python获取维基百科文章

我试图用Python的urllib获取Wikipedia文章:

f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes") s = f.read() f.close() 

但是,而不是HTML页面,我收到以下回应:错误 – 维基媒体基金会:

 Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to () Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT 

维基百科似乎阻止不是来自标准浏览器的请求。

任何人都知道如何解决这个问题?

您需要使用取代python std库中的urllib的urllib2来更改用户代理。

直接从例子

 import urllib2 opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] infile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes') page = infile.read() 

这不是解决具体问题的方法。 但是你可能会使用mwclient库( http://botwiki.sno.cc/wiki/Python:Mwclient )来代替。 那会容易得多。 特别是因为你会直接得到文章内容,而不需要你parsinghtml。

我自己用了两个项目,效果很好。

而不是试图欺骗维基百科,你应该考虑使用他们的高级API 。

如果你试图访问维基百科的内容(并不需要任何关于页面本身的特定信息),而不是使用API​​,你应该只需要调用index.php'action = raw'来获取wiki文本在:

http://en.wikipedia.org/w/index.php?; action = raw &title = Main_Page'

或者,如果您需要HTML代码,请使用“action = render”,如下所示:

http://en.wikipedia.org/w/index.php?; action = render &title = Main_Page'

您也可以定义一个部分,以便像“section = 3”那样获取部分内容。

然后,您可以使用urllib2模块访问它(如在所选答案中获得的那样)。 但是,如果您需要有关页面本身的信息(如修订版本),则可以更好地使用上面提到的mwclient。

如果您需要更多信息,请参阅MediaWiki常见问题 。

我用于任何站点的通用解决scheme是使用Firefox访问页面,并使用诸如Firebug之类的扩展来loggingHTTP请求的所有细节,包括任何cookie。

在你的程序中(在这种情况下,在Python中)你应该尝试发送一个类似于Firefox所需的HTTP请求。 这通常包括设置User-Agent,Referer和Cookie字段,但也可能有其他字段。

requests是真棒!

这里是如何获得HTML requests内容:

 import requests html = requests.get('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes').text 

完成!

尝试更改您在请求中发送的用户代理标题,如下所示:User-Agent:Mozilla / 5.0(X11; U; Linux i686; en-US; rv:1.9.0.1)Gecko / 2008072820 Ubuntu / 8.04(hardy) Firefox / 3.0.1(Linux Mint)

您不需要模拟浏览器用户代理; 任何用户代理都可以工作,而不是空白的。

 import urllib s = urllib.urlopen('http://en.wikipedia.org/w/index.php?action=raw&title=Albert_Einstein').read() 

这似乎适用于我而不更改用户代理。 没有“行动=原始”这不适合我。

?printable=yes请求页面会给你一个相对干净的HTML文档。 ?action=render给你正文HTML。 请求使用action=parse通过MediaWiki action APIparsing页面同样给出了正文HTML,但是如果您想要更好的控制, 请参阅parsingAPI帮助 。

如果你只是想要页面的HTML,所以你可以渲染它,更快,更好的是使用新的RESTBase API,它返回页面的cachingHTML表示。 在这种情况下, https://en.wikipedia.org/api/rest_v1/page/html/Albert_Einstein

截至2015年11月,您不必设置您的用户代理,但强烈鼓励 。 而且,几乎所有的维基媒体wiki 都需要HTTPS ,所以避免301redirect,并提出http请求。