有办法提取吗
Albert Einstein (/ˈælbərt ˈaɪnstaɪn/; German: ˈalbɐt ˈaɪnʃtaɪn; 14 March 1879– 18 April 1955) was a German-born theoretical physicist who developed the theory of general relativity, effecting a revolution in physics. ............. with over 150 non-scientific works. [6][8] His great intelligence and originality have made the word "Einstein" synonymous with genius. [9]
(主段落的整个输出,如果代码运行,则可见)
自动从以下代码输出?即使它是从另一个维基百科页面输出的:
import urllib2
import re, sys
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def stripHTMLTags(html):
html = re.sub(r'<{1}br{1}>', '\n', html)
s = MLStripper()
s.feed(html)
text = s.get_data()
if "External links" in text:
text, sep, tail = text.partition('External links')
if "External Links" in text:
text, sep, tail = text.partition('External Links')
text = text = text.replace("See also","\n\n See Also - \n")
text = text.replace("*","- ")
text = text.replace(".", ". ")
text = text.replace(" "," ")
text = text.replace(""" /
/ ""","")
return text
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()
print stripHTMLTags(page)
请原谅我糟糕的格式,代码(可能还有缩进),我现在使用的是3英寸显示器,还没有机会检查我自己的代码:p
也要感谢那些帮助我实现这一目标的人:)
我在这里留下我的答案,因为这正是OP所要求的。正确的方法是按照下面的the answer by @ChristophD中的建议使用
python-wikitools
。在我稍微修改了您问题中的代码以使用BeautifulSoup。还有其他选择。您可能还想试试lxml。在
我强烈建议不要对任何网站进行html抓取。在
这样做很痛苦,很容易崩溃,很多网站所有者不喜欢它。在
使用这个(python-wikitools)与wikipediaapi接口(从长远来看,这是您的最佳选择)。在
以下API请求返回纯文本页提取: https://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Albert%20Einstein&explaintext
相关问题 更多 >
编程相关推荐