Python爬蟲新手教程: 知乎文章圖片爬取器

1. 知乎文章圖片爬取器之二博客背景

昨天寫了知乎文章圖片爬取器的一部分代碼,針對知乎問題的答案json進行了數據抓取,博客中出現了部分寫死的內容,今天把那部分信息調整完畢,而且將圖片下載完善到代碼中去。html

首先,須要獲取任意知乎的問題,只須要你輸入問題的ID,就能夠獲取相關的頁面信息,好比最重要的合計有多少人回答問題。
問題ID爲以下標紅數字git

編寫代碼,下面的代碼用來檢測用戶輸入的是不是正確的ID,而且經過拼接URL去獲取該問題下面合計有多少答案。正則表達式

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  # 準備插入數據

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("查找到{}條數據".format(s.groups()[0]))
            return s.groups()[0]

if __name__ == '__main__':

    # 用死循環判斷用戶輸入的是不是數字
    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("沒有任何數據!")
Python資源分享qun 784758214 ,內有安裝包,PDF,學習視頻,這裏是Python學習者的彙集地,零基礎,進階,都歡迎

完善圖片下載部分,圖片下載地址在查閱過程當中發現,存在json字段的content中,咱們採用簡單的正則表達式將他匹配出來。細節以下圖展現json

編寫代碼吧,下面的代碼註釋請仔細閱讀,中間有一個小BUG,須要手動把pic3修改成pic2這個地方目前緣由不明確,多是我本地網絡的緣由,還有請在項目根目錄先建立一個imgs的文件夾,用來存儲圖片網絡

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
Python資源分享qun 784758214 ,內有安裝包,PDF,學習視頻,這裏是Python學習者的彙集地,零基礎,進階,都歡迎

運行結果爲學習

而後在玩知乎的過程當中,發現了好多好問題編碼

相關文章
相關標籤/搜索