python爬蟲(chóng)開(kāi)發(fā)之使用python爬蟲(chóng)庫(kù)requests,urllib與今日頭條搜索功能爬取搜索內(nèi)容實(shí)例
使用python爬蟲(chóng)庫(kù)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
#請(qǐng)求索引頁(yè)
def get_page_index(offset,keyword):
#傳送的數(shù)據(jù)
data={
'offset': offset,
'format': 'json',
'keyword': keyword,
'autoload': 'true',
'count': '20',
'cur_tab': 1
}
#自動(dòng)編碼為服務(wù)器可識(shí)別的url
url="https://www.toutiao.com/search_content/?"+urlencode(data)
#異常處理
try:
#獲取返回的網(wǎng)頁(yè)
response=requests.get(url)
#判斷網(wǎng)頁(yè)的狀態(tài)碼是否正常獲取
if response.status_code==200:
#返回解碼后的網(wǎng)頁(yè)
return response.text
#不正常獲取,返回None
return None
except RequestException:
#提示信息
print("請(qǐng)求索引頁(yè)出錯(cuò)")
return None
#解析請(qǐng)求的索引網(wǎng)頁(yè)數(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')
#圖集詳情頁(yè)請(qǐng)求
def get_page_detail(url):
#設(shè)置UA,模擬瀏覽器正常訪問(wèn)
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("請(qǐng)求詳情頁(yè)出錯(cuò)")
return None
#解析圖集詳情頁(yè)的數(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請(qǐng)求
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("請(qǐng)求圖片出錯(cuò)")
return None
#圖片保存
def save_image(content):
#判斷文件夾是否存在,不存在則創(chuàng)建
if '街拍' not in os.listdir():
os.makedirs('街拍')
#設(shè)置寫(xiě)入文件所在文件夾位置
os.chdir('E:\python寫(xiě)網(wǎng)路爬蟲(chóng)\CSDN爬蟲(chóng)學(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)頁(yè)獲取
html=get_page_index(offset,'街拍')
#圖集url
for url in parse_page_index(html):
if url!=None:
#圖集網(wǎng)頁(yè)詳情
html=get_page_detail(url)
#圖集內(nèi)容
result=parse_page_detail(html,url)
if __name__ == '__main__':
#創(chuàng)建訪問(wèn)的列表(0-9)頁(yè)
group=[i*10 for i in range(10)]
#創(chuàng)建多線程進(jìn)程池
pool=Pool()
#進(jìn)程池啟動(dòng),傳入的數(shù)據(jù)
pool.map(mian,group)
爬取圖片如下

本文主要講解了python爬蟲(chóng)庫(kù)requests、urllib與OS模塊結(jié)合使用爬取今日頭條搜索內(nèi)容的實(shí)例,更多關(guān)于python爬蟲(chóng)相關(guān)知識(shí)請(qǐng)查看下面的相關(guān)鏈接
- python爬蟲(chóng)爬取指定內(nèi)容的解決方法
- python爬蟲(chóng)爬取bilibili網(wǎng)頁(yè)基本內(nèi)容
- Python爬蟲(chóng)爬取百度搜索內(nèi)容代碼實(shí)例
- python爬取內(nèi)容存入Excel實(shí)例
- Python爬蟲(chóng)爬取新浪微博內(nèi)容示例【基于代理IP】
- python爬取網(wǎng)頁(yè)內(nèi)容轉(zhuǎn)換為PDF文件
- Python下使用Scrapy爬取網(wǎng)頁(yè)內(nèi)容的實(shí)例
- 基于Python實(shí)現(xiàn)web網(wǎng)頁(yè)內(nèi)容爬取的方法
相關(guān)文章
Django如何實(shí)現(xiàn)密碼錯(cuò)誤報(bào)錯(cuò)提醒
這篇文章主要介紹了Django如何實(shí)現(xiàn)密碼錯(cuò)誤報(bào)錯(cuò)提醒,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值2020-09-09
解讀torch.cuda.amp自動(dòng)混合精度訓(xùn)練之節(jié)省顯存并加快推理速度
這篇文章主要介紹了torch.cuda.amp自動(dòng)混合精度訓(xùn)練之節(jié)省顯存并加快推理速度問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
Python中字符串的基礎(chǔ)介紹及常用操作總結(jié)
字符串輸出格式與輸入的樣子相同,都是用撇號(hào)包裹,撇號(hào)和其它特殊字符用用反斜杠轉(zhuǎn)義。如果字符串中有單撇號(hào)而沒(méi)有雙撇號(hào)則用雙撇號(hào)包裹,否則應(yīng)該用單撇號(hào)包裹。后面要介紹的print語(yǔ)句可以不帶撇號(hào)或轉(zhuǎn)義輸出字符串2021-09-09
ChatGLM-6B+LangChain環(huán)境部署與使用實(shí)戰(zhàn)
這篇文章主要介紹了ChatGLM-6B+LangChain環(huán)境部署與使用方法,結(jié)合實(shí)例形式詳細(xì)分析了ChatGLM-6B+LangChain環(huán)境部署相關(guān)步驟、實(shí)現(xiàn)方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下2023-07-07
centos系統(tǒng)升級(jí)python 2.7.3
CentOS上安裝的python版本是2.6,不能滿足我運(yùn)行軟件的要求,所以對(duì)python進(jìn)行升級(jí)。Python的最新版本已經(jīng)是3.3,但是Python3的兼容性可能還有一定的問(wèn)題,所以還是升級(jí)到2.7較為保險(xiǎn)。2014-07-07

