python爬蟲開發(fā)之使用python爬蟲庫requests,urllib與今日頭條搜索功能爬取搜索內(nèi)容實例
使用python爬蟲庫requests,urllib爬取今日頭條街拍美圖
代碼均有注釋
import re,json,requests,os
from hashlib import md5
from urllib.parse import urlencode
from requests.exceptions import RequestException
from bs4 import BeautifulSoup
from multiprocessing import Pool
#請求索引頁
def get_page_index(offset,keyword):
#傳送的數(shù)據(jù)
data={
'offset': offset,
'format': 'json',
'keyword': keyword,
'autoload': 'true',
'count': '20',
'cur_tab': 1
}
#自動編碼為服務(wù)器可識別的url
url="https://www.toutiao.com/search_content/?"+urlencode(data)
#異常處理
try:
#獲取返回的網(wǎng)頁
response=requests.get(url)
#判斷網(wǎng)頁的狀態(tài)碼是否正常獲取
if response.status_code==200:
#返回解碼后的網(wǎng)頁
return response.text
#不正常獲取,返回None
return None
except RequestException:
#提示信息
print("請求索引頁出錯")
return None
#解析請求的索引網(wǎng)頁數(shù)據(jù)
def parse_page_index(html):
#json加載轉(zhuǎn)換
data=json.loads(html)
#數(shù)據(jù)為真,并且data鍵值存在與數(shù)據(jù)中
if data and 'data' in data.keys():
#遍歷返回圖集所在的url
for item in data.get('data'):
yield item.get('article_url')
#圖集詳情頁請求
def get_page_detail(url):
#設(shè)置UA,模擬瀏覽器正常訪問
head = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
#異常處理
try:
response=requests.get(url,headers=head)
if response.status_code==200:
return response.text
return None
except RequestException:
print("請求詳情頁出錯")
return None
#解析圖集詳情頁的數(shù)據(jù)
def parse_page_detail(html,url):
#異常處理
try:
#格式轉(zhuǎn)換與圖集標(biāo)題提取
soup=BeautifulSoup(html,'lxml')
title=soup.select('title')[0].get_text()
print(title)
#正則查找圖集鏈接
image_pattern = re.compile('gallery: (.*?),\n', re.S)
result = re.search(image_pattern, html)
if result:
#數(shù)據(jù)的優(yōu)化
result=result.group(1)
result = result[12:]
result = result[:-2]
#替換
result = re.sub(r'\\', '', result)
#json加載
data = json.loads(result)
#判斷數(shù)據(jù)不為空,并確保sub——images在其中
if data and 'sub_images' in data.keys():
#sub_images數(shù)據(jù)提取
sub_images=data.get('sub_images')
#列表數(shù)據(jù)提取
images=[item.get('url') for item in sub_images]
#圖片下載
for image in images:download_images(image)
#返回字典
return {
'title':title,
'url':url,
'images':images
}
except Exception:
pass
#圖片url請求
def download_images(url):
#提示信息
print('正在下載',url)
#瀏覽器模擬
head = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
#異常處理
try:
response = requests.get(url, headers=head)
if response.status_code == 200:
#圖片保存
save_image(response.content)
return None
except RequestException:
print("請求圖片出錯")
return None
#圖片保存
def save_image(content):
#判斷文件夾是否存在,不存在則創(chuàng)建
if '街拍' not in os.listdir():
os.makedirs('街拍')
#設(shè)置寫入文件所在文件夾位置
os.chdir('E:\python寫網(wǎng)路爬蟲\CSDN爬蟲學(xué)習(xí)\街拍')
#路徑,名稱,后綴
file_path='{0}/{1}.{2}'.format(os.getcwd(),md5(content).hexdigest(),'jpg')
#圖片保存
with open(file_path,'wb') as f:
f.write(content)
f.close()
#主函數(shù)
def mian(offset):
#網(wǎng)頁獲取
html=get_page_index(offset,'街拍')
#圖集url
for url in parse_page_index(html):
if url!=None:
#圖集網(wǎng)頁詳情
html=get_page_detail(url)
#圖集內(nèi)容
result=parse_page_detail(html,url)
if __name__ == '__main__':
#創(chuàng)建訪問的列表(0-9)頁
group=[i*10 for i in range(10)]
#創(chuàng)建多線程進(jìn)程池
pool=Pool()
#進(jìn)程池啟動,傳入的數(shù)據(jù)
pool.map(mian,group)
爬取圖片如下

本文主要講解了python爬蟲庫requests、urllib與OS模塊結(jié)合使用爬取今日頭條搜索內(nèi)容的實例,更多關(guān)于python爬蟲相關(guān)知識請查看下面的相關(guān)鏈接
相關(guān)文章
python神經(jīng)網(wǎng)絡(luò)facenet人臉檢測及keras實現(xiàn)
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)facenet人臉檢測及keras實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Python3 利用requests 庫進(jìn)行post攜帶賬號密碼請求數(shù)據(jù)的方法
今天小編就為大家分享一篇Python3 利用requests 庫進(jìn)行post攜帶賬號密碼請求數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
Python OpenCV 基于圖像邊緣提取的輪廓發(fā)現(xiàn)函數(shù)
這篇文章主要介紹了Python OpenCV 基于圖像邊緣提取的輪廓發(fā)現(xiàn)函數(shù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
Pytorch+PyG實現(xiàn)GraphSAGE過程示例詳解
這篇文章主要為大家介紹了Pytorch+PyG實現(xiàn)GraphSAGE過程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
python爬蟲URL重試機(jī)制的實現(xiàn)方法(python2.7以及python3.5)
今天小編就為大家分享一篇python爬蟲URL重試機(jī)制的實現(xiàn)方法(python2.7以及python3.5),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
Python使用Pandas和Matplotlib按中值對箱形圖進(jìn)行排序
箱形圖是可視化數(shù)據(jù)分布的強(qiáng)大工具,因為它們提供了對數(shù)據(jù)集內(nèi)的散布、四分位數(shù)和離群值的洞察,在本文中,我們將探索如何在Python中使用Pandas和Matplotlib按中值對箱形圖進(jìn)行排序,需要的朋友可以參考下2025-04-04

