多线程爬虫
来自CloudWiki
多线程与网络爬虫
Python的多线程对于IO密集型代码比较友好,网络爬虫能够在获取网页的过程中使用多线程,从而加快速度。
下面将以获取访问量最大的1000个中文网站的速度为例,通过和单线程的爬虫比较,证实多线程方法在网络爬虫速度上的提升。这1000个访问量最大的中文网站是在Alexca.cn上获取的,地址如下:https://github.com/Santostang/PythonScraping/blob/master/Cha%207%20-%E6%8F%90%E5%8D%87%E7%88%AC%E8%99%AB%E7%9A%84%E9%80%9F%E5%BA%A6/alexa.txt
简单单线程爬虫
首先,以单线程(单进程)的方式抓取这1000个网页,代码如下:
import requests import time link_list = [] with open('alexa.txt','r') as file: file_list = file.readlines() for eachone in file_list: link = eachone.split('\t')[1] link = link.replace('\n','') link_list.append(link) start = time.time() for eachone in link_list: try: r=requests.get(eachone) print(r.status_code,eachone) except Exception as e: print('Error: ',e) end = time.time() print('串行的总时间为:',end-start)
参考文档:《Python爬虫:从入门到实践》