it编程 > 前端脚本 > Ajax

爬取今日头条Ajax请求

149人参与 2024-05-19 Ajax

网址:https://www.toutiao.com/

搜索头条

可以得到这个网址:

https://www.toutiao.com/search/?keyword=%e8%a1%97%e6%8b%8d

开发者工具查看:

我们在搜索中并没有发现上面的文字,那么我们可以初步判定,这个由ajax加载,然后渲染出来的。此时切换到xhr过滤,可以看到确实是ajax请求。

观察请求的特点,发现只有offset是改变的,而且一次加20,。

我们可以用它来控制数据分页,然后把图片下载下来。代码如下:

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 = 'https://www.toutiao.com/search_content/?'+urlencode(params)
  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) 等待一秒

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对代码网的支持。如果你想了解更多相关内容请查看下面相关链接

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

Ajax报错400的参考解决办法

05-19

ajax实现页面的局部加载

05-19

$.ajax中contentType: “application/json” 的用法详解

05-19

Ajax实现表格中信息不刷新页面进行更新数据

05-19

解决ajax异步请求返回的是字符串问题

05-19

Ajax引擎 ajax请求步骤详细代码

05-19

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论