资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

使用Ajax请求怎么爬取今日头条-创新互联

本篇文章给大家分享的是有关使用Ajax请求怎么爬取今日头条,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

创新互联公司:公司2013年成立为各行业开拓出企业自己的“网站建设”服务,为千余家公司企业提供了专业的成都网站建设、网站设计、网页设计和网站推广服务, 定制网站由设计师亲自精心设计,设计的效果完全按照客户的要求,并适当的提出合理的建议,拥有的视觉效果,策划师分析客户的同行竞争对手,根据客户的实际情况给出合理的网站构架,制作客户同行业具有领先地位的。

代码如下:


import requests
import os
from urllib.parse import urlencode
from hashlib import md5
from multiprocessing.pool import Pool
from requests import codes
def get_page(offset):
  params = {
    "offset":offset,
    "format":"json",
    "keyword":"街拍",
    "autoload":"true",
    "count":"20",
    "cur_tab":"1",
    "from":"search_tab"
  }
  url = '/tupian/20230522/&
  try:
    response = requests.get(url)
    if response.status_code == 200:
      # print(url)
      return response.json()
  except requests.ConnectionError:
    return None
# get_page(0)
def get_images(json):
  if json.get('data'):
    for item in json.get('data'):
      if item.get('cell_type') is not None:
        continue
      title = item.get('title')
      images = item.get('image_list')
      for image in images:
        yield {
          'title':title,
          'image':'https:' + image.get('url'),
        }
def save_image(item):
  #os.path.sep  路径分隔符‘//'
  img_path = 'img' + os.path.sep + item.get('title')
  if not os.path.exists(img_path):
    os.makedirs(img_path)
  try:
    resp = requests.get(item.get('image'))
    # print(type(resp))
    if codes.ok == resp.status_code:
      file_path = img_path + os.path.sep + '{file_name}.{file_suffix}'.format(
        file_name=md5(resp.content).hexdigest(),#md5是一种加密算法获取图片的二进制数据,以二进制形式写入文件
        file_suffix='jpg')
      if not os.path.exists(file_path):
        with open(file_path,'wb')as f:
          f.write(resp.content)
          print('Downladed image path is %s' % file_path)
      else:
        print('Already Downloaded',file_path)
  except requests.ConnectionError:
    print('Failed to Save Image,item %s' % item)
def main(offset):
  json = get_page(offset)
  for item in get_images(json):
    print(item)
    save_image(item)
GROUP = 0
GROUP_END = 2
if __name__ == '__main__':
  pool = Pool()
  groups = ([x*20 for x in range(GROUP,GROUP_END)])
  pool.map(main,groups)  #将groups一个个调出来传给main函数
  pool.close()
  pool.join()   #保证子进程结束后再向下执行 pool.join(1) 等待一秒

以上就是使用Ajax请求怎么爬取今日头条,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。


网站标题:使用Ajax请求怎么爬取今日头条-创新互联
分享链接:http://cdkjz.cn/article/djjeih.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220