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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?