1. 程式人生 > >python爬取知乎回答

python爬取知乎回答

1. 安裝庫

htmlparser用來解析html。

Beautiful Soup 是一個可以從 HTML 或 XML 檔案中提取資料的 Python 庫。

pip install beautifulsoup4

Selenium 是瀏覽器自動化測試框架,使用它來模擬使用者操作。

利用 pip 安裝 selenium

pip install -U selenium

2. 模擬使用者進行滾動和點選操作

使用JS控制滾動條的位置:

window.scrollTo(x,y);

豎向滾動條置底

 window.scrollTo(0,document.body
.scrollHeight) time.sleep(2)

向下滑動後延遲兩毫秒等待頁面載入。

在頁面上通過審查,找到檢視更多回答的html程式碼

<button class="Button QuestionMainAction"
type="button">檢視更多回答</button>

通過

driver.find_element_by_css_selector('button.QuestionMainAction').click()

來選中並點選這個按鈕。

3. html檔案結構化

將html檔案結構化並儲存,原頁面的html解析並存儲下來

通過prettify()將html結構化,之後儲存在本地的txt檔案中。

4. 儲存並下載圖片

注意我們的目的,就是爬取回答下的圖片,其他的都不需要。

還是右鍵審查,可以發現每張圖片上面都有的node,沒錯,這裡面存有圖片的高清URL和縮圖URL。

每個元素都被html entity編碼了,所以我們要將其解碼如下。

html.parser.unescape

之後就可以將圖片URL儲存下來。

最後下載圖片。

urllib.request.urlretrieve

5. 結果展示

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

6. 程式碼


from selenium import
webdriver import time import urllib.request from bs4 import BeautifulSoup import html.parser def main(): driver = webdriver.Chrome() # 開啟瀏覽器 driver.get("https://www.zhihu.com/question/40273344") # 開啟想要爬取的知乎頁面 # 模擬使用者操作 def execute_times(times): for i in range(times): driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(2) 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("./output/rawfile/raw_result.txt", 'w',encoding="utf-8") as girls: # 儲存路徑裡的資料夾需要事先建立。 girls.write(result_bf) girls.close() print("爬取回答頁面成功!!!") with open("./output/rawfile/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標籤成功!!!") img_soup = BeautifulSoup(noscript_all, 'html.parser') img_nodes = img_soup.find_all('img') with open("./output/rawfile/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, "./output/image/" + str(count) + ".jpg") # 一個一個下載圖片 count += 1 img_meta.close() print("圖片下載成功") if __name__ == '__main__': main()