Python爬蟲-面向知乎的答案提取和圖片下載
需求描述:爬取知乎的答案,爬取并下載一個問題下所有回答中的圖片。
實現平臺:開發工具PyCharm2017,語言版本Python3.6,Chrome谷歌瀏覽器。
基本原理:1.發送請求,獲取網頁HTML源碼;解析HTML,獲取數據;保存數據。2
模擬瀏覽器登錄,獲取并解析HTML,獲取數據。利用Python中的庫即可便捷實現。
功能實現1:知乎答案爬取
實現思路:
1. 首先實現安裝好第三方模塊requests和bs4并調用。
2. 其次設置Http請求頭,利用requests訪問網頁獲取到源代碼,利用bs模塊中的BeautifulSoup得到解析過后的html。
3. 隨后,分別通過對照網頁源代碼中標簽內容進行匹配,分別獲取問題標題、問題內容、點贊數以及答案等內容。
4. 最后進行包括知乎答案等信息的打印。
分別對應上述思路進行代碼編寫。
1. 調用第三方模塊。
#-*- coding: UTF-8 -*-
# 爬取知乎答案
import requests
from bs4 import BeautifulSoup
2. 設置Http請求頭:可以在Chrome谷歌瀏覽器的網頁中的任意地方按下F12,打開chrome自帶的調試工具,在調試工具中選擇network標簽,F5刷新網頁后在左邊找到該網頁url,點擊該url,選擇Headers,就可以看到當前網頁的Http頭。復制到header={}中。
獲取源代碼并解析:利用requests和BeautifulSoup實現,并返回解析后的body。
#獲取網頁body里的內容
def get_content(url , data = None):
# 設置Http請求頭,根據自己電腦查一下
header={
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'zh-CN,zh;q=0.8',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
}
req = requests.get(url, headers=header)
req.encoding = 'utf-8'
bs = BeautifulSoup(req.text, "html.parser") # 創建BeautifulSoup對象
body = bs.body #
return body
3. 標簽內容進行class匹配:問題標題——QuestionHeader-title,問題內容——RichText ztext,點贊量——Button VoteButton VoteButton—up,問題回答——ContentItem-time。


#獲取問題標題
def get_title(html_text):
data = html_text.find('h1', {'class':' QuestionHeader-title '}) #匹配標簽
return data.string.encode('utf-8')
#獲取問題內容
def get_question_content(html_text):
data = html_text.find('span', {'class': 'RichText ztext'})
print (data.string)
if data.string is None:
out = ''
for datastring in data.strings:
datastring = datastring.encode('utf-8')
out = out + datastring.encode('utf-8')
print ('內容:\n' + out)
else:
print ('內容:\n' + data.string.encode('utf-8'))
#獲取點贊數
def get_answer_agree(body):
agree = body.find('button',{'class': 'Button VoteButton VoteButton--up'})
agree_html = BeautifulSoup(str(agree), "html.parser")
all_buttons = agree_html.find_all("button", {"class": "Button VoteButton VoteButton--up"})
one_button = all_buttons[0]
agree_number = one_button["aria-label"]
print(agree_number)
#獲取答案
def get_response(html_text):
out1 = ''
response = html_text.find_all('div', {'class': 'ContentItem-time'})
for index in range(len(response)):
#獲取標簽
answerhref = response[index].find('a', {'target': '_blank'})
if not(answerhref['href'].startswith('javascript')):
url = 'http:' + answerhref['href']
body = get_content(url)
get_answer_agree(body)
answer = body.find('span', {'class': 'RichText ztext CopyrightRichText-richText css-hnrfcf'})
if answer.string is None:
out = ''
for datastring in answer.strings:
datastring = datastring.encode('utf-8')
out = out + '\n' + str(datastring,encoding = 'utf-8')
else:
print (answer.string.encode('utf-8'))
out1 = out1 + '\n' + out
return url + '\n' + out1
4. 結果輸出打印:以一個網址為例,調用之前編寫的函數,進行信息的獲取和打印。
# 輸入要爬取的網址
URL_target = 'https://www.zhihu.com/question/505503990/answer/2276487889'
html_text = get_content(URL_target)
title = get_title(html_text)
print ("標題:" + str(title,encoding = 'utf-8') + '\n')
data = get_response(html_text)
print (data)

功能實現2:知乎圖片下載
實現思路:
1. 首先實現安裝好chromedriver模擬人為登錄瀏覽器,模擬登錄網頁,中途拿手機掃碼登錄。
2. 安裝好模塊selenium、time、urllib.request 、bs4 和html.parser并調用。
3. 利用chromedriver打開瀏覽器并登錄知乎,利用bs模塊中的BeautifulSoup得到解析過后的html。
4. 隨后,找到照片并進行下載。
5. 保存所有圖片。
思路是先模擬登錄網頁,(中途拿手機掃碼登錄),然后逐步爬取所有回答。
1.下載對應Chrome版本的chromedriver。
通過chrome://version/查看版本,下載chromedriver后解壓安裝。詳細可以參考這個說明。
selenium 安裝與 chromedriver 安裝 :https://www.cnblogs.com/lfri/p/10542797.html
我的Chrome版本是:94.0.4606.71(正式版本)(64 位),對應文件夾應該放在
C:\Program Files\Google\Chrome\Application
2.分別對應上述思路進行代碼編寫,安裝好模塊并調用。
# 爬取知乎問題下的所有圖片
from selenium import webdriver
import time
import urllib.request
from bs4 import BeautifulSoup
import html.parser
3.自動化打開瀏覽器并掃碼登錄知乎,并解析網頁 HTML 信息,查找所有的noscript標簽。
def main():
# 確保文件夾中有chromedriver.exe,有的在C:\Program Files x86
chromedriver = 'C:\Program Files\Google\Chrome\Application\chromedriver.exe'
driver = webdriver.Chrome(chromedriver)
time.sleep(5)
driver.get("https://www.zhihu.com/question/287084175") # 打開想要爬取的知乎頁面
time.sleep(5)
# 模擬用戶操作
def execute_times(times):
for i in range(times):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(3)
try:
driver.find_element_by_css_selector('button.QuestionMainAction').click()
print("page" + str(i))
time.sleep(1)
except:
break
# 執行次數
execute_times(5)
# 原網頁的信息
result_raw = driver.page_source # 這是原網頁 HTML 信息
result_soup = BeautifulSoup(result_raw, 'html.parser')# 然后將其解析
result_bf = result_soup.prettify() # 結構化原 HTML 文件
with open("D:/python安裝包/PycharmProjects/zhihutupian/raw_result.txt", 'w',encoding="utf-8") as raw_result: # 存儲路徑里的文件夾需要事先創建。
raw_result.write(result_bf)
raw_result.close()
print("爬取回答頁面成功!!!")
with open("D:/python安裝包/PycharmProjects/zhihutupian/noscript_meta.txt", 'wb') as noscript_meta:
noscript_nodes = result_soup.find_all('noscript') # 找到所有<noscript>node
noscript_inner_all = ""
for noscript in noscript_nodes:
noscript_inner = noscript.get_text() # 獲取<noscript>node內部內容
noscript_inner_all += noscript_inner + "\n"
noscript_all = html.parser.unescape(noscript_inner_all).encode('utf-8') # 將內部內容轉碼并存儲
noscript_meta.write(noscript_all)
noscript_meta.close()
print("爬取noscript標簽成功!!!")
4.查找所有圖片并命名下載。
img_soup = BeautifulSoup(noscript_all, 'html.parser')
img_nodes = img_soup.find_all('img')
with open("D:/python安裝包/PycharmProjects/zhihutupian/img_meta.txt", 'w') as img_meta:
count = 0
for img in img_nodes:
if img.get('src') is not None:
img_url = img.get('src')
line = str(count) + "\t" + img_url + "\n"
img_meta.write(line)
urllib.request.urlretrieve(img_url, "D:/python安裝包/PycharmProjects/zhihutupian/" + str(count) + ".jpg") # 一個一個下載圖片
count += 1
img_meta.close()
print("圖片下載成功")
if __name__ == '__main__':
main()
5.最后進行包括知乎圖片的保存。


最后,有相關爬蟲需求歡迎通過公眾號聯系我們.
公眾號: 320科技工作室
工程師必備
- 項目客服
- 培訓客服
- 平臺客服
TOP




















