Python基于分析Ajax請(qǐng)求實(shí)現(xiàn)抓取今日頭條街拍圖集功能示例
本文實(shí)例講述了Python基于分析Ajax請(qǐng)求實(shí)現(xiàn)抓取今日頭條街拍圖集功能。分享給大家供大家參考,具體如下:

代碼:
import os
import re
import json
import time
from hashlib import md5
from multiprocessing import Pool
import requests
from requests.exceptions import RequestException
from pymongo import MongoClient
# 配置信息
OFFSET_START = 0 # 爬去頁(yè)面的起始下標(biāo)
OFFSET_END = 20 # 爬去頁(yè)面的結(jié)束下標(biāo)
KEYWORD = '街拍' # 搜索的關(guān)鍵字
# mongodb相關(guān)配置
MONGO_URL = 'localhost'
MONGO_DB = 'toutiao' # 數(shù)據(jù)庫(kù)名稱(chēng)
MONGO_TABLE = 'jiepai' # 集合名稱(chēng)
# 圖片保存的文件夾名稱(chēng)
IMAGE_PATH = 'images'
headers = {
"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
}
client = MongoClient(host=MONGO_URL)
db = client[MONGO_DB]
jiepai_table = db[MONGO_TABLE]
if not os.path.exists(IMAGE_PATH):
os.mkdir(IMAGE_PATH)
def get_html(url, params=None):
try:
response = requests.get(url, params=params, headers=headers)
if response.status_code == 200:
return response.text
return None
except RequestException as e:
print("請(qǐng)求%s失敗: " % url, e)
return None
# 獲取索引頁(yè)內(nèi)容
def get_index_page(offset, keyword):
basic_url = 'http://www.toutiao.com/search_content/'
params = {
'offset': offset,
'format': 'json',
'keyword': keyword,
'autoload': 'true',
'count': 20,
'cur_tab': 3
}
return get_html(basic_url, params)
def parse_index_page(html):
'''
解析索引頁(yè)內(nèi)容
返回: 索引頁(yè)中包含的所有詳情頁(yè)url
'''
if not html:
return
data = json.loads(html)
if 'data' in data:
for item in data['data']:
article_url = item['article_url']
if 'toutiao.com/group' in article_url:
yield article_url
# 獲取詳情頁(yè)
def get_detail_page(url):
return get_html(url)
# 解析詳情頁(yè)
def parse_detail_page(url, html):
'''
解析詳情頁(yè)
返回對(duì)應(yīng)的標(biāo)題,url和包含的圖片url
'''
title_reg = re.compile('<title>(.*?)</title>')
title = title_reg.search(html).group(1)
gallery_reg = re.compile('var gallery = (.*?);')
gallery = gallery_reg.search(html)
if gallery and 'sub_images' in gallery.group(1):
images = json.loads(gallery.group(1))['sub_images']
image_list = [image['url'] for image in images]
return {
'title': title,
'url': url,
'images': image_list
}
return None
def save_to_mongodb(content):
jiepai_table.insert(content)
print("存儲(chǔ)到mongdob成功", content)
def download_images(image_list):
for image_url in image_list:
try:
response = requests.get(image_url)
if response.status_code == 200:
save_image(response.content)
except RequestException as e:
print("下載圖片失敗: ", e)
def save_image(content):
'''
對(duì)圖片的二進(jìn)制內(nèi)容做hash,構(gòu)造圖片路徑,以此保證圖片不重復(fù)
'''
file_path = '{0}/{1}/{2}.{3}'.format(os.getcwd(),
IMAGE_PATH, md5(content).hexdigest(), 'jpg')
# 去除重復(fù)的圖片
if not os.path.exists(file_path):
with open(file_path, 'wb') as f:
f.write(content)
def jiepai(offset):
html = get_index_page(offset, KEYWORD)
if html is None:
return
page_urls = list(parse_index_page(html))
# print("詳情頁(yè)url列表:" )
# for page_url in page_urls:
# print(page_url)
for page in page_urls:
print('get detail page:', page)
html = get_detail_page(page)
if html is None:
continue
content = parse_detail_page(page, html)
if content:
save_to_mongodb(content)
download_images(content['images'])
time.sleep(1)
print('-------------------------------------')
if __name__ == '__main__':
offset_list = range(OFFSET_START, OFFSET_END)
pool = Pool()
pool.map(jiepai, offset_list)
備注:
其實(shí)通過(guò)url請(qǐng)求返回的json數(shù)據(jù)中已經(jīng)包含了圖片列表
import requests
basic_url = 'http://www.toutiao.com/search_content/?offset={}&format=json&keyword=%E8%A1%97%E6%8B%8D&autoload=true&count=20&cur_tab=3'
url = basic_url.format(0)
html = requests.get(url).json()
items = html['data']
for item in items:
title = item['media_name']
image_list = [image_detail['url'] for image_detail in item['image_detail']]
print(title, image_list)
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Python Socket編程技巧總結(jié)》、《Python URL操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門(mén)與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python通過(guò)ssh-powershell監(jiān)控windows的方法
這篇文章主要介紹了python通過(guò)ssh-powershell監(jiān)控windows的方法,涉及Python操作ssh-powershell的相關(guān)技巧,需要的朋友可以參考下2015-06-06
使用sklearn進(jìn)行對(duì)數(shù)據(jù)標(biāo)準(zhǔn)化、歸一化以及將數(shù)據(jù)還原的方法
今天小編就為大家分享一篇使用sklearn進(jìn)行對(duì)數(shù)據(jù)標(biāo)準(zhǔn)化、歸一化以及將數(shù)據(jù)還原的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
Python數(shù)組拼接np.concatenate實(shí)現(xiàn)過(guò)程
這篇文章主要介紹了Python數(shù)組拼接np.concatenate實(shí)現(xiàn)過(guò)程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
python中使用ctypes調(diào)用so傳參設(shè)置遇到的問(wèn)題及解決方法
這篇文章主要介紹了python中使用ctypes調(diào)用so傳參設(shè)置,本文較詳細(xì)的給大家介紹了遇到問(wèn)題及解決方案,需要的朋友可以參考下2019-06-06
如何用 Python 子進(jìn)程關(guān)閉 Excel 自動(dòng)化中的彈窗
這篇文章主要介紹了如何用 Python 子進(jìn)程關(guān)閉 Excel 自動(dòng)化中的彈窗,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-05-05
numpy.bincount用于復(fù)數(shù)權(quán)重的方法
numpy.bincount是NumPy庫(kù)中的一個(gè)函數(shù),它用于計(jì)算整數(shù)數(shù)組中每個(gè)值的出現(xiàn)次數(shù),numpy.bincount函數(shù)在統(tǒng)計(jì)整數(shù)數(shù)組中每個(gè)值的出現(xiàn)次數(shù)或權(quán)重和時(shí)非常有用,本文給大家介紹numpy.bincount如何用于復(fù)數(shù)權(quán)重,感興趣的朋友跟隨小編一起看看吧2023-11-11

