基于线程池提升request模块效率的方法-创新互联

这篇文章主要讲解了基于线程池提升request模块效率的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

创新互联于2013年开始,先为古田等服务建站,古田等地企业,进行企业商务咨询服务。为古田企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

普通方法:爬取梨视频

import re
import time
import random
import requests
from lxml import etree

start_time = time.time()

url = "https://www.pearvideo.com/category_3"
headers = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
}

ex = 'srcUrl="(.*?)",vdoUrl=srcUrl'

def request_video(url):
  """
  向视频链接发送请求
  """
  return requests.get(url=url, headers=headers).content

def save_video(content):
  """
  将视频的二进制数据保存到本地
  """
  video_name = str(random.randint(100, 999)) + ".mp4"
  with open(video_name, 'wb') as f:
    f.write(content)

    
# 获取首页源码
page_text = requests.get(url=url, headers=headers).text

tree = etree.HTML(page_text)
li_list = tree.xpath('//ul[@class="listvideo-list clearfix"]/li')

video_url_list = list()
for li in li_list:
  detail_url = "https://www.pearvideo.com/" + li.xpath('./div/a/@href')[0]
  
  # 获取该视频页面的源码
  detail_page_text = requests.get(url=detail_url, headers=headers).text
  
  # 正则匹配视频的URL
  video_url = re.findall(ex, detail_page_text, re.S)[0]
  video_url_list.append(video_url)
  
  content = request_video(video_url)
  save_video(content)


print("执行耗时: ", time.time() - start_time)

标题名称:基于线程池提升request模块效率的方法-创新互联
文章转载:http://azwzsj.com/article/hgccs.html