python多线程网络爬虫_Python网络爬虫多线程和多处理

简而言之,我的网络爬虫有两个主要工作。收集器和爬虫程序,收集器将收集每个站点的所有url项并存储非重复的url。爬虫程序将从存储器中获取url,提取所需的数据并将其存储起来。在2 MachinesBot machine -> 8 core, Physical Linux OS (No VM on this machine)

Storage machine -> mySql with clustering (VM for clustering), 2 databases (url and data); url database on port 1 and data port 2

目的:对100个站点进行爬虫,以减少瓶颈情况First case: Collector *request(urllib) all sites , collect the url

items for each sites and * insert if it's non duplicated url to

Storage machine on port 1. Crawler *get the url from storage port 1 ,

*request site and extract needed data and *store it's back on port 2

这导致了请求网站和mySql连接的连接瓶颈Second case: Instead of inserting across the machine, Collector store

the url on my own mini database file system.There is no *read a huge

file(use os command technic) just *write (append) and *remove header

of the file.

这导致连接请求网站和I/O(读、写)瓶颈(可能是)

这两种情况也有CPU限制的原因收集和爬行100个网站

正如我听说的I/O边界使用多线程,CPU边界使用多处理

两者都怎么样?好斗的?有什么想法或建议吗?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的Python线爬虫示例: ```python import requests import threading from queue import Queue # 定义一个全局变量用来存储爬取到的数据 data = [] # 定义一个线程锁,防止多个线程同时写入数据导致数据错乱 lock = threading.Lock() # 定义一个队列,用来存储待爬取的URL url_queue = Queue() # 定义一个爬取线程类 class CrawlerThread(threading.Thread): def __init__(self, url_queue): super().__init__() self.url_queue = url_queue def run(self): while True: # 从队列中获取一个URL url = self.url_queue.get() try: # 发送请求并解析响应数据 response = requests.get(url) content = response.text # 对响应数据进行处理(此处省略) # ... # 将处理后的数据存入全局变量 with lock: data.append(processed_data) # 标记该URL已被处理 self.url_queue.task_done() except Exception as e: print(f"Error occurred while crawling {url}: {e}") # 如果发生错误,将该URL重新放回队列 self.url_queue.put(url) self.url_queue.task_done() # 定义一个入口函数 def main(): # 初始化待爬取的URL列表 urls = ["http://www.example.com/page{}".format(i) for i in range(1, 11)] # 将URL列表添加到队列中 for url in urls: url_queue.put(url) # 创建多个爬取线程并启动 for i in range(5): t = CrawlerThread(url_queue) t.start() # 阻塞主线程,直到所有URL都被处理完毕 url_queue.join() # 输出爬取结果 print(data) if __name__ == '__main__': main() ``` 以上示例中,我们定义了一个`CrawlerThread`类来表示爬取线程,定义了一个`url_queue`队列来存储待爬取的URL,定义了一个`data`列表来存储爬取到的数据,以及定义了一个`lock`线程锁来保证多个线程访问`data`时不会出现数据错乱的情况。 在`main`函数中,我们首先将待爬取的URL列表添加到`url_queue`队列中,然后创建多个`CrawlerThread`实例并启动它们。最后,我们使用`url_queue.join()`方法来阻塞主线程,直到所有的URL都被处理完毕。 在`CrawlerThread`类的`run`方法中,我们使用`self.url_queue.get()`方法从`url_queue`队列中获取一个URL,然后发送请求并解析响应数据。如果处理过程中出现错误,我们将该URL重新放回队列中,以便后续线程重新处理。如果处理成功,我们将处理后的数据存入`data`列表中,并使用`self.url_queue.task_done()`方法标记该URL已被处理完毕。 需要注意的是,在多线爬虫中,如果爬取的网站对IP访问频率有限制,可能会导致IP被封禁的情况。因此,在实际应用中,我们需要合理设置线程数量和请求频率,以避免被封禁的情况发生。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值