【问题标题】:Faster parsing with Python使用 Python 更快地解析
【发布时间】: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


    【解决方案1】:

    根据您需要从页面中提取的内容,您可能不需要完整的 DOM。也许您可以使用HTMLParser(Python3 中的html.parser)逃脱。它应该更快。

    我会将获取页面与解析页面分离,例如两个池,一个是获取页面并填充队列,另一个池是从队列中获取页面并解析它们。这会稍微更好地使用可用资源,但不会有很大的加速。如果服务器以更大的延迟开始服务页面,则副作用是,您仍然可以让工作人员忙于排长队。

    【讨论】:

    • 感谢您的回答。由于我使用 Python 2.7,是否有一些替代 Python 3 的 HTMLParser 的方法?谢谢
    • @Milan,HTMLParser 是 2.7,它在 python 3 中被重命名为 html.parser
    • @Milan,将 IO 与处理分离也可能是值得的,考虑到您已经进行了多处理,这甚至不是很大的努力
    猜你喜欢
    • 2016-03-09
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2017-05-20
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    相关资源
    最近更新 更多