首页 > 其他分享 >【爬虫实例3】异步爬取大量数据

【爬虫实例3】异步爬取大量数据

时间:2022-08-14 16:02:23浏览次数:52  
标签:__ 异步 url resp 爬虫 爬取 num data 页面

1、导入模块

import requests
import csv
from concurrent.futures import ThreadPoolExecutor

2、先获取第一个页面的内容

分析得到该页面的数据是从getPriceData.html页面获取,并保存在csv文件中

得到url地址后,提取第一个页面内容

def download(url, num):
    resp = requests.post(url).json()
    for i in resp['list']:
        temp = [i['prodName'], i['lowPrice'], i['highPrice'], i['avgPrice'], i['place'], i['unitInfo'], i['pubDate']]
        csvwrite.writerow(temp)
   


if __name__ == "__main__":
    url = 'http://www.xinfadi.com.cn/getPriceData.html'
    download(url)
    print('success')

** 此为第一个页面信息提取:**

3、获取更多的信息

分析页面数据显示规律,请求地址时页面携带页码和需要显示数据的条数,一共17362页,每页20条数据

设置100个线程提取17362页数据,同时每次请求时传入页码

def download(url, num):
    data = {
        "limit": 20,
        "current": num
    }
    resp = requests.post(url, data=data).json()
    for i in resp['list']:
        temp = [i['prodName'], i['lowPrice'], i['highPrice'], i['avgPrice'], i['place'], i['unitInfo'], i['pubDate']]
        csvwrite.writerow(temp)
    print(f'{num}页提取完成')


if __name__ == "__main__":
    url = 'http://www.xinfadi.com.cn/getPriceData.html'
    # 设置100个线程
    with ThreadPoolExecutor(100) as t:
        for i in range(1, 17363):
            t.submit(download(url, i))
    print('success')

4、完整代码

4、完整代码

# 1、提取单页面

import requests
import csv
from concurrent.futures import ThreadPoolExecutor

f = open("data.csv", mode="w", encoding="utf-8")
csvwrite = csv.writer(f)


def download(url, num):
    data = {
        "limit": 20,
        "current": num
    }
    resp = requests.post(url, data=data).json()
    for i in resp['list']:
        temp = [i['prodName'], i['lowPrice'], i['highPrice'], i['avgPrice'], i['place'], i['unitInfo'], i['pubDate']]
        csvwrite.writerow(temp)
    print(f'{num}页提取完成')


if __name__ == "__main__":
    url = 'http://www.xinfadi.com.cn/getPriceData.html'
    # 设置100个线程
    with ThreadPoolExecutor(100) as t:
        for i in range(1, 17363):
            t.submit(download(url, i))
    print('success')

以下为第1页~第199页数据:

标签:__,异步,url,resp,爬虫,爬取,num,data,页面
From: https://www.cnblogs.com/nnguhx/p/16585560.html

相关文章

  • 【爬虫实例1】晋江小说免费章节爬取
    1、导入模块importrequestsfromlxmlimportetree2、获取小说名字以及章节地址#请求路由地址b_resp=requests.get(b_url,headers=headers)#网页编码设置b_......
  • 【爬虫实例2】91网视频爬取
    1、导入模块importrequestsimportre2、获取m3u8文件#url地址url='http://www.wwmulu.com/rj/xhcl/play-1-1.html'#正则表达式obj=re.compile(r'<spancla......
  • 爬虫数据分析-Xpath
    1.环境安装:-pipinstalllxml2.如何实例化一个etree对象:fromlxmlimportetree(1)将本地的html文档中的源码数据加载到etree对象中:etree.parse(filePath)(2)可......
  • 事件一些补充 以及同步异步概念
    事件补充事件onload事件:当网页中的所有资源都加在完成之后执行这个事件通常是将script标签放到head标签中的时候使用。因为放在head中默认是获取不到body中的内容的,但是......