【发布时间】:2016-01-13 11:25:54
【问题描述】:
我正在尝试从一个网页解析数据。此网页允许您(根据 robots.txt)每分钟发送 2000 个请求。
问题是我尝试的一切都太慢了。该服务器的响应非常快。
from multiprocessing.pool import ThreadPool as Pool
import datetime
import lxml.html as lh
from bs4 import BeautifulSoup
import requests
with open('products.txt') as f:
lines = f.readlines()
def update(url):
html = requests.get(url).content # 3 seconds
doc = lh.parse(html) # almost 12 seconds (with commented line below)
soup = BeautifulSoup(html) # almost 12 seconds (with commented line above)
pool = Pool(10)
for line in lines[0:100]:
pool.apply_async(update, args=(line[:-1],))
pool.close()
now = datetime.datetime.now()
pool.join()
print datetime.datetime.now() - now
正如我在代码中评论的那样 - 当我尝试只为 100 个网址执行 html = requests.get(url) 时,时间非常好 - 不到 3 秒。
问题是当我想使用一些解析器时 - html 的预处理大约需要 10 秒甚至更多,这太多了。
你会推荐我什么来缩短时间?
编辑:我尝试使用SoupStrainer - 它稍微快一点,但没有什么明显的 - 9 秒。
html = requests.get(url).content
product = SoupStrainer('div',{'class': ['shopspr','bottom']})
soup = BeautifulSoup(html,'lxml', parse_only=product)
【问题讨论】:
标签: python parsing web-scraping beautifulsoup lxml