【问题标题】:How to accelerate Beautifulsoup in Python?如何在 Python 中加速 Beautifulsoup?
【发布时间】:2017-05-06 12:18:18
【问题描述】:

我尝试在 Python 中使用 Beautifulsoup 解析 50 000 个 url。 解析循环工作:

我发现解析一页的时间是 15 - 18 秒。从页面我抓取了大约 20 个元素。

Beautifulsoup 为什么运行这么慢?如何在 Python 中加速 Beautifulsoup?

【问题讨论】:

  • 使用lxml库或者使用beautiful的lxml解析器

标签: python python-2.7 beautifulsoup


【解决方案1】:

确保您了解自己的瓶颈。

第一个也是主要的问题不是 HTML 解析 - 它是“解析工作在循环中”。

这意味着代码是同步/阻塞的 - 在您处理完当前网址之前,您不会处理下一个网址。这绝对是不可扩展

要解决这个问题,请切换到异步方法 - 例如切换到 Scrapy web-scraping 框架 - 这是目前扩展 web-scraping 项目最自然的举措。

另见:

【讨论】:

    【解决方案2】:

    并行处理。

    例如

    import Queue
    import threading 
    
    # will execute parrallel
    def taskProcess(q, url):
        q.put(beautifulSoupFunction(url))
    
    urls = ["http://url1.com", "http://url2.com"]
    
    q = Queue.Queue()
    
    for u in urls:
        t = threading.Thread(target=taskProcess, args = (q,u))
        t.daemon = True
        t.start()
    
    s = q.get()
    print s
    

    【讨论】:

    • 需要我把它放到线程中吗? q.put(beautifulSoupFunction(url))?或以下所有代码为:title = soup.select('.document-title > .id-app-title')[0].text?
    • 我的意思是如何把这段代码放到Q: `soup = BeautifulSoup(content, 'html.parser') web_site = "" title = soup.select('.document-title > . id-app-title')[0].text`
    • 坦率地说,这是一个不同的问题,并不是我不想回答这个问题。
    • 在 Python 3 中出现错误:NameError: name 'Thread' is not defined
    • 您可以执行以下回复吗? >>> 导入线程 >>> def p(s): ... print s ... >>> t = threading.Thread(target=p, args=(["Hello"])) >>> t.运行 > >>> t.run() Hello >>>
    猜你喜欢
    • 2020-11-01
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 2017-04-24
    • 2011-03-11
    • 2015-01-13
    相关资源
    最近更新 更多