本篇文章為大家展示了使用Python怎么爬取知乎圖片,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

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 # 準(zhǔn)備插入數(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中,我們采用簡單的正則表達(dá)式將他匹配出來。細(xì)節(jié)如下圖展示

編寫代碼吧,下面的代碼注釋請仔細(xì)閱讀,中間有一個小BUG,需要手動把pic3修改為pic2這個地方目前原因不明確,可能是我本地網(wǎng)絡(luò)的原因,還有請在項目根目錄先創(chuàng)建一個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: # 這個地方進(jìn)行了硬編碼
                  f.write(content)
                print("圖片下載完成", end="\n")
          except Exception as e:
            print(e.args)
      else:
        pass上述內(nèi)容就是使用Python怎么爬取知乎圖片,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
                分享文章:使用Python怎么爬取知乎圖片-創(chuàng)新互聯(lián)
                
                文章源于:http://www.chinadenli.net/article12/djcegc.html
            
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計公司、App設(shè)計、全網(wǎng)營銷推廣、網(wǎng)站維護、軟件開發(fā)、響應(yīng)式網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容