【问题标题】:Fastest way to read and process 100,000 URLs in Python在 Python 中读取和处理 100,000 个 URL 的最快方法
【发布时间】:2016-10-15 23:10:20
【问题描述】:

我有一个包含 100,000 个 URL 的文件,我需要请求然后处理。与请求相比,处理需要的时间不可忽略,所以简单地使用多线程似乎只能给我部分加速。从我读到的内容来看,我认为使用multiprocessing 模块或类似的东西会提供更大幅度的加速,因为我可以使用多个内核。我猜我想使用多个进程,每个进程都有多个线程,但我不知道该怎么做。

这是我当前的代码,使用线程(基于What is the fastest way to send 100,000 HTTP requests in Python?):

from threading import Thread
from Queue import Queue
import requests
from bs4 import BeautifulSoup
import sys

concurrent = 100

def worker():
    while True:
        url = q.get()
        html = get_html(url)
        process_html(html)
        q.task_done()

def get_html(url):
    try:
        html = requests.get(url, timeout=5, headers={'Connection':'close'}).text
        return html
    except:
        print "error", url
        return None

def process_html(html):
    if html == None:
        return
    soup = BeautifulSoup(html)
    text = soup.get_text()
    # do some more processing
    # write the text to a file

q = Queue(concurrent * 2)
for i in range(concurrent):
    t = Thread(target=worker)
    t.daemon = True
    t.start()
try:
    for url in open('text.txt'):
        q.put(url.strip())
    q.join()
except KeyboardInterrupt:
    sys.exit(1)

【问题讨论】:

  • .@Gus 使用并发 100 并没有得到任何加速。它们都同时出去,令人惊讶的是——它们都回来等待操作系统进程。你能做的,就是两步。使用本地线程 (i/o) 拉取所有内容,然后使用核心*2 进行多进程。 (或者,你会遇到同样的问题)
  • 我明白了。所以也许我可以把它分成两个脚本——有一个只使用多线程的脚本,并将原始 HTML 保存到文件中。然后有另一个是多处理,处理文件,然后在完成后删除它们。不确定这是否是最好的解决方案?
  • 这就是我会做的。 ——然后做。 --- 否则你可以切换语言并使用 nodejs 来抓取——但这完全是一个不同的过程。
  • 链接具有误导性——它没有说明 HTML 处理。使用 lxml.html 或请求。 (如果你知道 jquery -- pyquery)

标签: python multithreading http concurrency multiprocessing


【解决方案1】:

如果文件不大于您的可用内存,则不要使用“打开”方法打开它,而是使用 mmap (https://docs.python.org/3/library/mmap.html)。它的速度与您使用内存而不是文件的速度相同。

with open("test.txt") as f:
    mmap_file = mmap.mmap(f.fileno(), 0)
    # code that does what you need
    mmap_file.close()

【讨论】:

    猜你喜欢
    • 2016-06-16
    • 2018-08-28
    • 2011-02-07
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2015-06-10
    • 2021-05-29
    • 2017-02-12
    相关资源
    最近更新 更多