hhhhqqq1111 2021-05-12 18:21 采纳率: 91.7%
浏览 52
已采纳

如何在爬取网页数据时用多线程?(python)

如何在爬取网页数据时用多线程?(python)

  • 写回答

6条回答 默认 最新

  • CSDN专家-HGJ 2021-05-12 23:49
    关注

    可以使用concurrent.futures的ThreadPoolExecutor,用一个线程池执行异步调用。例:

    import requests
    from bs4 import BeautifulSoup as bs
    import time
    from concurrent.futures import ThreadPoolExecutor
    cookies = {
        '__cfduid': 'xxx',
        'PHPSESSID': 'xxx',
    }#从页面分析获取
    
    headers = {
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
        'DNT': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.44',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
        'Referer': 'http://www.enagames.com/escape-game/top10newgames-rescue-the-tiger-2',
        'Accept-Language': 'en-US;q=0.6',
    }
    
    response = requests.get('http://www.enagames.com/escape-game/top10newgames-rescue-the-tiger-2',headers=headers, cookies=cookies, verify=False)
    soup=bs(response.text,'html.parser')
    
    game_link = set([x['href']  for x in soup.select(
        'div.home_game_image_featured center a')])
    gl=list(game_link)
    
    def get_swf(url):
        r=requests.get(url,headers=headers,cookies=cookies)
    
        s=bs(r.text,'html.parser')
    
        sl =s.select_one('div#flash_container1 object param')['value']
        with open(f'./{url.split("/")[-1]}.swf', 'wb') as f:
            try:
                req = requests.get(sl, headers=headers)
                f.write(req.content)
            except:
                pass
    with ThreadPoolExecutor(max_workers=5)  as ex:
        ex.map(get_swf,gl[:5])   
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂