可以应用几个修复程序(无需更改当前使用的模块):使用lxml解析器而不是html5lib-它要快得多(而且还要多出3个muches)
使用SoupStrainer只解析文档的一部分(注意,html5lib不支持SoupStrainer-它总是缓慢地解析整个文档)
下面是更改后代码的外观。简短的性能测试显示至少3倍的改进:import urllib2
import xml.etree.cElementTree as ET
from datetime import date
from bs4 import SoupStrainer, BeautifulSoup
import nltk
from dateutil.rrule import rrule, DAILY
from nltk.corpus import stopwords
def main_parser():
a = b = date(2014, 3, 27)
articles = ET.Element("articles")
for dt in rrule(DAILY, dtstart=a, until=b):
url = "http://www.reuters.com/resources/archive/us/" + dt.strftime("%Y") + dt.strftime("%m") + dt.strftime(
"%d") + ".html"
links = SoupStrainer("div", "headlineMed")
soup = BeautifulSoup(urllib2.urlopen(url), "lxml", parse_only=links)
article_date = ET.SubElement(articles, "article_date")
article_date.text = str(dt)
for link in soup.find_all('a'):
if not 'video' in link['href']:
try:
article_time = ET.SubElement(article_date, "article_time")
article_time.text = str(link.text[-11:])
article_header = ET.SubElement(article_time, "article_name")
article_header.text = str(link.text)
article_link = ET.SubElement(article_time, "article_link")
article_link.text = str(link['href']).encode('utf-8')
try:
article_text = ET.SubElement(article_time, "article_text")
article_text.text = str(remove_stop_words(extract_article(link['href']))).encode('ascii', 'ignore')
except Exception:
pass
except Exception:
pass
tree = ET.ElementTree(articles)
tree.write("~/Documents/test.xml", "utf-8")
def extract_article(url):
paragraphs = SoupStrainer('p')
soup = BeautifulSoup(urllib2.urlopen(url), "lxml", parse_only=paragraphs)
return soup.text
def remove_stop_words(text):
text = nltk.word_tokenize(text)
filtered_words = [w for w in text if not w in stopwords.words('english')]
return ' '.join(filtered_words)
请注意,我已经从extract_article()中删除了正则表达式处理,看起来您可以从p标记中获取整个文本。在
我可能已经介绍了一些问题-请检查是否一切都是正确的。在
另一种解决方案是使用lxml来处理从解析(replacebeautifulSoup)到创建xml(replacexml.etree.ElementTree)的所有事情。在
另一个解决方案(绝对是最快的)是切换到Scrapyweb抓取web框架。
它很简单而且很快。你可以想象,里面有各种各样的电池。例如,有链接提取器、XML导出器、数据库管道等值得一看。在
希望有帮助。在