python 多线程爬取网站数据利用线程池

"""
@author: wangxingchun
多线程(线程池)
下载数据
"""
【python 多线程爬取网站数据利用线程池】import requests
import csv
from concurrent.futures import ThreadPoolExecutor as tp
#创建一个csv文件,注意创建writer对象"csv.writer()"
f = open('xinfadi.csv','w',encoding='utf8')
csvwrite = csv.writer(f)
#如果写入txt文件,不需要创建writer对象 。
# f = open('xinfadidata.txt','w',encoding='utf8')
#创建一个函数,以页码做为参数
def down(n_page):
url = 'http://www.xinfadi.com.cn/getPriceData.html'
 
data = https://www.isolves.com/it/cxkf/yy/Python/2022-02-08/{'count': 428225,'current': n_page,'limit': 20}
 
resp = requests.post(url,data=https://www.isolves.com/it/cxkf/yy/Python/2022-02-08/data)
datas =resp.json()
 
#通过分析数据嵌套情况,获取数据 。此处可在网页开发工具json数据中查看分析 。
for i in range(len(datas['list'])):
name = datas['list'][i]['prodName']
highPrice = datas['list'][i]['highPrice']
lowPrice = datas['list'][i]['lowPrice']
pubDate = datas['list'][i]['pubDate']
place = datas['list'][i]['place']
csvwrite.writerow((name,highPrice,lowPrice,pubDate,place))#writerow要求写入的是可迭代对象
# f.writelines(f'{name},{highPrice},{lowPrice},{pubDate},{place}n')
resp.close()
 
if __name__ == '__main__':
with tp(50) as t: #创建线程池,
for n in range(1,101): #遍历数据网页
t.submit(down,n) #提交给线程池,进行多线程下载
print(f'共{n}页数据下载完毕!')
f.close()




    推荐阅读