2019-09-17 14:14:01 5283瀏覽
今天千鋒扣丁學(xué)堂Python培訓(xùn)老師給大家分享一篇關(guān)于爬取知乎圖片代碼實現(xiàn)解析的詳細介紹,首先,需要獲取任意知乎的問題,只需要你輸入問題的ID,就可以獲取相關(guān)的頁面信息,比如最重要的合計有多少人回答問題。import requests import re import pymongo import time DATABASE_IP = '127.0.0.1' DATABASE_PORT = 27017 DATABASE_NAME = 'sun' client = pymongo.MongoClient(DATABASE_IP,DATABASE_PORT) db = client.sun db.authenticate("dba", "dba") collection = db.zhihuone # 準備插入數(shù)據(jù) BASE_URL = "https://www.zhihu.com/question/{}" def get_totle_answers(article_id): headers = { "user-agent": "需要自己補全 Mozilla/5.0 (Windows NT 10.0; WOW64)" } with requests.Session() as s: with s.get(BASE_URL.format(article_id),headers=headers,timeout=3) as rep: html = rep.text pattern =re.compile( '<meta itemProp="answerCount" content="(\d*?)"/>') s = pattern.search(html) print("查找到{}條數(shù)據(jù)".format(s.groups()[0])) return s.groups()[0] if __name__ == '__main__': # 用死循環(huán)判斷用戶輸入的是否是數(shù)字 article_id = "" while not article_id.isdigit(): article_id = input("請輸入文章ID:") totle = get_totle_answers(article_id) if int(totle)>0: zhi = ZhihuOne(article_id,totle) zhi.run() else: print("沒有任何數(shù)據(jù)!")
完善圖片下載部分,圖片下載地址在查閱過程中發(fā)現(xiàn),存在json字段的content中,我們采用簡單的正則表達式將他匹配出來。細節(jié)如下圖展示:
def download_img(self,data): ## 下載圖片 for item in data["data"]: content = item["content"] pattern = re.compile('<noscript>(.*?)</noscript>') imgs = pattern.findall(content) if len(imgs) > 0: for img in imgs: match = re.search('<img src="(.*?)"', img) download = match.groups()[0] download = download.replace("pic3", "pic2") # 小BUG,pic3的下載不到 print("正在下載{}".format(download), end="") try: with requests.Session() as s: with s.get(download) as img_down: # 獲取文件名稱 file = download[download.rindex("/") + 1:] content = img_down.content with open("imgs/{}".format(file), "wb+") as f: # 這個地方進行了硬編碼 f.write(content) print("圖片下載完成", end="\n") except Exception as e: print(e.args) else: pass
運行結(jié)果為:
【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】 【掃碼進入Python全棧開發(fā)免費公開課】
查看更多關(guān)于"Python開發(fā)資訊"的相關(guān)文章>