<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Python 抓取知乎幾千張小姐姐圖片是什么體驗?

          共 8717字,需瀏覽 18分鐘

           ·

          2021-03-26 08:14

          文 | 某某白米飯

          來源:Python 技術(shù)「ID: pythonall」

          知乎上有許多關(guān)于顏值、身材的話題,有些話題的回復(fù)數(shù)甚至高達幾百上千,擁有成千上萬的關(guān)注者與被瀏覽數(shù)。如果我們在摸魚的時候欣賞這些話題將花費大量的時間,可以用 Python 制作一個下載知乎回答圖片的小腳本,將圖片下載到本地。

          請求 URL 分析

          首先打開 F12 控制臺面板,看到照片的 URL 都是 https://pic4.zhimg.com/80/xxxx.jpg?source=xxx 這種格式的。

          滾動知乎頁面向下翻頁,找到一個帶 limit,offset 參數(shù)的 URL 請求。

          檢查 Response 面板中的內(nèi)容是否包含了圖片的 URL 地址,其中圖片地址 URL 存在 data-original 屬性中。

          提取圖片的 URL

          從上圖可以看出圖片的地址存放在 content 屬性下的 data-original 屬性中。

          下面代碼將獲取圖片的地址,并寫入文件。

          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("文件中共有{}個不重復(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é)語

          今天的文章用 Python 爬蟲制作了一個小腳本,如果小伙伴們覺得文章有趣且有用,點個 在看 支持一下吧!

          PS公號內(nèi)回復(fù)「Python」即可進入Python 新手學(xué)習(xí)交流群,一起 100 天計劃!


          老規(guī)矩,兄弟們還記得么,右下角的 “在看” 點一下,如果感覺文章內(nèi)容不錯的話,記得分享朋友圈讓更多的人知道!

          代碼獲取方式

          識別文末二維碼,回復(fù):210325

          瀏覽 66
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  青青草原视频在线 | 美女干逼免费的 | 黄片操逼视频 | 丰润少妇在线观看视频 | 国产激情无码 |