溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用Ajax請(qǐng)求怎么爬取今日頭條

發(fā)布時(shí)間:2021-06-11 14:08:46 來(lái)源:億速云 閱讀:177 作者:Leah 欄目:web開(kāi)發(fā)

本篇文章給大家分享的是有關(guān)使用Ajax請(qǐng)求怎么爬取今日頭條,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。

代碼如下:

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是一種加密算法獲取圖片的二進(jìn)制數(shù)據(jù),以二進(jìn)制形式寫入文件
        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一個(gè)個(gè)調(diào)出來(lái)傳給main函數(shù)
  pool.close()
  pool.join()   #保證子進(jìn)程結(jié)束后再向下執(zhí)行 pool.join(1) 等待一秒

以上就是使用Ajax請(qǐng)求怎么爬取今日頭條,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI