
來(lái)源:【公眾號(hào)】
Python技術(shù)
知乎上有許多關(guān)于顏值、身材的話題,有些話題的回復(fù)數(shù)甚至高達(dá)幾百上千,擁有成千上萬(wàn)的關(guān)注者與被瀏覽數(shù)。如果我們?cè)诿~(yú)的時(shí)候欣賞這些話題將花費(fèi)大量的時(shí)間,可以用 Python 制作一個(gè)下載知乎回答圖片的小腳本,將圖片下載到本地。
首先打開(kāi) F12 控制臺(tái)面板,看到照片的 URL 都是 https://pic4.zhimg.com/80/xxxx.jpg?source=xxx 這種格式的。
滾動(dòng)知乎頁(yè)面向下翻頁(yè),找到一個(gè)帶 limit,offset 參數(shù)的 URL 請(qǐng)求。
檢查 Response 面板中的內(nèi)容是否包含了圖片的 URL 地址,其中圖片地址 URL 存在 data-original 屬性中。
從上圖可以看出圖片的地址存放在 content 屬性下的 data-original 屬性中。
下面代碼將獲取圖片的地址,并寫(xiě)入文件。
import re import requests import os import urllib.request import ssl from urllib.parse import urlsplit from os.path import basename import json
ssl._create_default_https_context = ssl._create_unverified_context
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
'Accept-Encoding': 'gzip, deflate' } def get_image_url(qid, title): answers_url = 'https://www.zhihu.com/api/v4/questions/'+str(qid)+'/answers?include=data%5B*%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cattachment%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Cis_labeled%2Cpaid_info%2Cpaid_info_content%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_recognized%3Bdata%5B*%5D.mark_infos%5B*%5D.url%3Bdata%5B*%5D.author.follower_count%2Cbadge%5B*%5D.topics%3Bdata%5B*%5D.settings.table_of_content.enabled&offset={}&limit=10&sort_by=default&platform=desktop' offset = 0 session = requests.Session()
while True:
page = session.get(answers_url.format(offset), headers = headers)
json_text = json.loads(page.text)
answers = json_text['data']
offset += 10 if not answers:
print('獲取圖片地址完成')
return pic_re = re.compile('data-original="(.*?)"', re.S)
for answer in answers:
tmp_list = []
pic_urls = re.findall(pic_re, answer['content'])
for item in pic_urls:
# 去掉轉(zhuǎn)移字符 pic_url = item.replace("", "")
pic_url = pic_url.split('?')[0]
# 去重復(fù) if pic_url not in tmp_list:
tmp_list.append(pic_url)
for pic_url in tmp_list:
if pic_url.endswith('r.jpg'):
print(pic_url)
write_file(title, pic_url) def write_file(title, pic_url): file_name = title + '.txt' f = open(file_name, 'a')
f.write(pic_url + 'n')
f.close()
示例結(jié)果:
下面代碼將讀取文件中的圖片地址并下載。
def read_file(title):
file_name = title + '.txt' pic_urls = []
# 判斷文件是否存在
if not os.path.exists(file_name):
return pic_urls
with open(file_name, 'r') as f:
for line in f:
url = line.replace("n", "")
if url not in pic_urls:
pic_urls.append(url)
print("文件中共有{}個(gè)不重復(fù)的 URL".format(len(pic_urls)))
return pic_urls
def download_pic(pic_urls, title):
# 創(chuàng)建文件夾
if not os.path.exists(title):
os.makedirs(title)
error_pic_urls = []
success_pic_num = 0 repeat_pic_num = 0 index = 1 for url in pic_urls:
file_name = os.sep.join((title,basename(urlsplit(url)[2])))
if os.path.exists(file_name):
print("圖片{}已存在".format(file_name))
index += 1 repeat_pic_num += 1 continue
try:
urllib.request.urlretrieve(url, file_name)
success_pic_num += 1 index += 1 print("下載{}完成!({}/{})".format(file_name, index, len(pic_urls)))
except:
print("下載{}失?。?{}/{})".format(file_name, index, len(pic_urls)))
error_pic_urls.append(url)
index += 1 continue
print("圖片全部下載完畢!(成功:{}/重復(fù):{}/失敗:{})".format(success_pic_num, repeat_pic_num, len(error_pic_urls)))
if len(error_pic_urls) > 0:
print('下面打印失敗的圖片地址')
for error_url in error_pic_urls:
print(error_url)
結(jié)語(yǔ)
今天的文章用 Python 爬蟲(chóng)制作了一個(gè)小腳本,如果小伙伴們覺(jué)得文章有趣且有用,點(diǎn)個(gè) 轉(zhuǎn)發(fā) 支持一下吧!
數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
LSTM 模型輸入長(zhǎng)度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長(zhǎng)序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠(chéng)摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡(jiǎn)稱 BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測(cè)分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢(shì)預(yù)判? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代,預(yù)測(cè)分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭(zhēng)搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢(shì)性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢(shì)性檢驗(yàn)如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢(shì)與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢(shì)變化以及識(shí)別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國(guó)內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對(duì)策略? 長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場(chǎng)調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場(chǎng)調(diào)研是企業(yè)洞察市場(chǎng)動(dòng)態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場(chǎng)調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書(shū)考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動(dòng)力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動(dòng)力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開(kāi)啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03