繁体   English   中英

Python多线程网络爬网

[英]Python multithreading web crawling

我有一个简单的Web搜寻器 ,每秒可爬行约4个(特定)网站。 如果我在两个不同的Python IDE中运行脚本,则可以使速度加倍,因为这两个程序都以每秒〜4的速度运行代码。 为什么我的代码运行得比预期的慢? 还是因为我使用一种愚蠢的方法通过同时使用两个不同的IDE使我的脚本使用多线程/多处理而更快?

我使用的是Python 3.5.2。

对于工作线程池来说,这听起来像是一项艰巨的任务。

请参阅: Python:多处理模块

如注释中所述,所有这些都与线程有关。

现在为您的程序提供了一个解决方案:

import requests
import threading

class Crawler:
    def __init__(self, url):
        self.url = url
        self.session = requests.Session()

    def crawl(self):
        page = self.session.get(url)
        # Do your crawling here

with open('urls.txt', 'r') as f: # Assuming you use a file with a list of URLs
    for url in f:
        while(threading.active_count() > 20): # Use 20 threads
            time.sleep(0.1)
        c = Crawler(url)
        t = threading.Thread(target = c.crawl())

请注意threading.active_count()也计入主线程。

而且,您应该在HTTP请求中使用超时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM