Python知乎熱門話題資料的爬取實戰

來源:互聯網
上載者:User

標籤: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知乎熱門話題資料的爬取實戰

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.