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')