標籤:class query 有一個 源碼 .text 類比 win64 css web
import requests
from pyquery import PyQuery as pq
url = ‘https://www.zhihu.com/explore‘
headers = {
‘user-agent‘:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}
# 為了讓網頁能類比瀏覽器的操作來設定一個headers擷取網頁源碼
html = requests.get(url, headers=headers).text
# 初始化,使用pyQuery來把html放到解析庫裡進行解析
doc = pq(html)
# 進行pyquery解析(裡面放的是css選取器參數)對class裡有兩個參數來進行解析
items = doc(‘.explore-feed.feed-item‘).items()
# 迴圈遍曆篩選後的資料
for item in items:
# 提取裡面的問題
question = item.find(‘h2‘).text()
# 提取裡面的作者
author = item.find(‘.author-link-line‘).text()
# 提取裡面的回複的內容,這裡注意一下,在內容的上面有一個textarea被hidden了
answer = pq(item.find(‘.content‘).html()).text()
# 方法一
# 檔案的儲存以txt文本儲存
file = open(‘explore.txt‘, ‘a‘, encoding=‘utf-8‘)
# 檔案的寫入
file.write(‘\n‘.join([question, author, answer]))
# 每一個內容用特殊符號隔開
file.write(‘\n‘ + ‘=‘ * 50 + ‘\n‘)
# 檔案的關閉
file.close()
# 方式二
# 簡寫的方法這樣可以不用去關閉檔案,系統已經封裝好了關閉的方法
with open(‘explore.txt‘, ‘a‘, encoding=‘utf-8‘) as file:
file.write(‘\n‘.join([question, author, answer]))
file.write(‘\n‘ + ‘=‘ * 50 + ‘\n‘)
Python知乎熱門話題資料的爬取實戰