日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

爬虫实战:要不是热爱学习,谁会爬小姐姐。分析Ajax来爬取今日头条街拍美图(python)

發(fā)布時(shí)間:2024/9/30 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 爬虫实战:要不是热爱学习,谁会爬小姐姐。分析Ajax来爬取今日头条街拍美图(python) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

有些網(wǎng)頁(yè)我們請(qǐng)求的html代碼并沒(méi)有我們?cè)跒g覽器里看到的內(nèi)容。
因?yàn)橛行┬畔⑹峭ㄟ^(guò)Ajax加載并通過(guò)JavaScript渲染生成的。

一.目標(biāo)站點(diǎn)分析

頭條街拍

查看的Ajax請(qǐng)求
選擇network 勾選preserve log 再勾選XHR ,數(shù)據(jù)鏈接如左側(cè)aid格式

在data下面能夠找到title

我們網(wǎng)頁(yè)不斷下滑,發(fā)現(xiàn)請(qǐng)求有offset有20,40,60變化。如圖。
我們可以認(rèn)為改變offset的值就能拿到不同數(shù)據(jù)。

通過(guò)觀察data,發(fā)現(xiàn)數(shù)據(jù)是json數(shù)據(jù)。

實(shí)戰(zhàn)

一.抓取索引頁(yè)內(nèi)容
1.查看URL
藍(lán)色為基本url,其他為參數(shù)

這些參數(shù)在下圖

急需下拉網(wǎng)頁(yè),只有offset在變化,每次變化20

獲取html代碼如下

from urllib.parse import urlencode import requests from requests.exceptions import ConnectionErrordef get_page(offest,keyword):#獲取請(qǐng)求并返回解析頁(yè)面,offest,keyword為可變參數(shù)params = {'aid': '24','app_name': 'web_search','offset': offest,#頁(yè)數(shù)'format': 'json','keyword': keyword,#關(guān)鍵詞,本例子為街拍'autoload': 'true','count': '20','en_qc': '1','cur_tab': '1','from': 'search_tab','pd': 'synthesis','timestamp': '1612660795006','_signature': '_02B4Z6wo00f01bVt4zgAAIDCfdEqJspzHQm1SeeAAA1FfgsJs85FLGn5fddPtscCGmt-RCmotIguRxATrRA1jejsf0LuGWhNYZDSWZIqUdhBN1ivlGKkDtAdcHKqYiKRWjlQZt4s9AU2aI2d0c'}headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36','x-requested-with': 'XMLHttpRequest'}base_url = 'https://www.toutiao.com/api/search/content/?'url = base_url + urlencode(params)try:response = requests.get(url,headers = headers)if response.status_code == 200 :return response.textexcept ConnectionError:print('程序錯(cuò)誤')return Nonedef main():base_url = 'https://www.toutiao.com/api/search/content/?'html=get_page(0,'街拍')print(html) if __name__ =='__main__':main() 可以發(fā)現(xiàn)結(jié)果中有很多超鏈接

二.數(shù)據(jù)解析
回到瀏覽器,查看返回結(jié)果Respnse響應(yīng),數(shù)據(jù)格式為json格式

在Preview找到data

對(duì)data進(jìn)行展開(kāi),其中的0,1,2.。均為一組街拍

展開(kāi)0
圖片url在image_list里

圖片名titlie

#數(shù)據(jù)解析 import json def parse_page_index(html):data=json.loads(html)#轉(zhuǎn)換為json對(duì)象if data and 'data'in data.keys():#判斷響應(yīng)里的data是否存在for item in data.get('data'): # 用item循環(huán)每一條,即0,1,2...# 這里需要判斷image_list是否為空title = item.get('title')if 'image_list' in item and item['image_list'] != []:images = item['image_list']for image in images:yield {'image': image.get('url'),'title': title} # 返回的一個(gè)字典

yield用法見(jiàn)例子
返回的是一個(gè)可以迭代的對(duì)象

def getnum(n):i = 0while i <= n:yield ii += 1 a = getnum(5) print(a) for i in a:print(i)

三.圖片保存

import os from hashlib import md5 def save_image(item):#os.path模塊主要用于文件的屬性獲取,exists是“存在”的意思,#所以顧名思義,os.path.exists()就是判斷括號(hào)里的文件夾'picture'+str(offset)是否存在的意思,括號(hào)內(nèi)的可以是文件路徑。if not os.path.exists(item.get('title')):#判斷當(dāng)前文件夾下是否有該文件os.mkdir(item.get('title'))#如果不存在就創(chuàng)建該文件夾try:response=requests.get(item['image']) #get函數(shù)獲取圖片鏈接地址,requests發(fā)送訪問(wèn)請(qǐng)求,上面那個(gè)字典if response.status_code==200:file_path='{0}/{1}.{2}'.format(item.get('title'),md5(response.content).hexdigest(),'jpg')# md5摘要算法(哈希算法),通過(guò)摘要算法得到一個(gè)長(zhǎng)度固定的數(shù)據(jù)塊。將文件保存時(shí),通過(guò)哈希函數(shù)對(duì)每個(gè)文件進(jìn)行文件名的自動(dòng)生成。# md5() 獲取一個(gè)md5加密算法對(duì)象# hexdigest() 獲取加密后的16進(jìn)制字符串if not os.path.exists(file_path):with open(file_path,'wb') as f:f.write(response.content)print('圖片保存路徑是: ', file_path)else:print('圖片已經(jīng)下載',file_path)except requests.ConnectionError:print('圖片保存失敗')

md5(response.content).hexdigest()摘要算法(哈希算法),通過(guò)摘要算法得到一個(gè)長(zhǎng)度固定的數(shù)據(jù)塊。將文件保存時(shí),通過(guò)哈希函數(shù)對(duì)每個(gè)文件進(jìn)行文件名的自動(dòng)生成。
示例

from hashlib import md5hash_functions = [md5] def get_hash_code(s):result = []hash_obj = md5(s)hash_hex = hash_obj.hexdigest()result.append((hash_obj.name, hash_hex, len(hash_hex)))return resultif __name__ == '__main__':s = "123"result = get_hash_code(s.encode("utf-8"))print(result)

總的代碼

from urllib.parse import urlencode import requests from requests.exceptions import ConnectionError import json def get_page(offest,keyword):#獲取請(qǐng)求并返回解析頁(yè)面,offest,keyword為可變參數(shù)params = {'aid': '24','app_name': 'web_search','offset': offest,#頁(yè)數(shù)'format': 'json','keyword': keyword,#關(guān)鍵詞,本例子為街拍'autoload': 'true','count': '20','en_qc': '1','cur_tab': '1','from': 'search_tab','pd': 'synthesis','timestamp': '1612660795006','_signature': '_02B4Z6wo00f01bVt4zgAAIDCfdEqJspzHQm1SeeAAA1FfgsJs85FLGn5fddPtscCGmt-RCmotIguRxATrRA1jejsf0LuGWhNYZDSWZIqUdhBN1ivlGKkDtAdcHKqYiKRWjlQZt4s9AU2aI2d0c'}headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36','x-requested-with': 'XMLHttpRequest'}base_url = 'https://www.toutiao.com/api/search/content/?'url = base_url + urlencode(params)try:response = requests.get(url,headers = headers)if response.status_code == 200 :return response.textexcept ConnectionError:print('程序錯(cuò)誤')return None #數(shù)據(jù)解析 import json def parse_page_index(html):data=json.loads(html)#轉(zhuǎn)換為json對(duì)象if data and 'data'in data.keys():#判斷響應(yīng)里的data是否存在for item in data.get('data'): # 用item循環(huán)每一條,即0,1,2...# 這里需要判斷image_list是否為空title = item.get('title')if 'image_list' in item and item['image_list'] != []:images = item['image_list']for image in images:yield {'image': image.get('url'),'title': title} # 返回一個(gè)字典import os from hashlib import md5 def save_image(item):#os.path模塊主要用于文件的屬性獲取,exists是“存在”的意思,#所以顧名思義,os.path.exists()就是判斷括號(hào)里的文件夾'picture'+str(offset)是否存在的意思,括號(hào)內(nèi)的可以是文件路徑。if not os.path.exists(item.get('title')):#判斷當(dāng)前文件夾下是否有該文件os.mkdir(item.get('title'))#如果不存在就創(chuàng)建該文件夾try:response=requests.get(item['image']) #get函數(shù)獲取圖片鏈接地址,requests發(fā)送訪問(wèn)請(qǐng)求,上面那個(gè)字典if response.status_code==200:file_path='{0}/{1}.{2}'.format(item.get('title'),md5(response.content).hexdigest(),'jpg')# md5摘要算法(哈希算法),通過(guò)摘要算法得到一個(gè)長(zhǎng)度固定的數(shù)據(jù)塊。將文件保存時(shí),通過(guò)哈希函數(shù)對(duì)每個(gè)文件進(jìn)行文件名的自動(dòng)生成。# md5() 獲取一個(gè)md5加密算法對(duì)象# hexdigest() 獲取加密后的16進(jìn)制字符串if not os.path.exists(file_path):with open(file_path,'wb') as f:f.write(response.content)print('圖片保存路徑是: ', file_path)else:print('圖片已經(jīng)下載',file_path)except requests.ConnectionError:print('圖片保存失敗')def main():for offest in range(0, 60, 20):html = get_page(offest, '街拍')a = parse_page_index(html)for item in a:save_image(item)if __name__ =='__main__':main() 結(jié)果文件夾 打開(kāi)一個(gè)文件夾

文件夾太多,我們修改為一個(gè)文件夾

結(jié)果

結(jié)果文件夾


作者:電氣-余登武。
碼字不易,請(qǐng)點(diǎn)個(gè)贊再走。

與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖

總結(jié)

以上是生活随笔為你收集整理的爬虫实战:要不是热爱学习,谁会爬小姐姐。分析Ajax来爬取今日头条街拍美图(python)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。