這是我參與8月更文挑戰的第4天,活動詳情查看:8月更文挑戰html
網址:知乎熱榜 python
開發環境:win十、python3.7正則表達式
開發工具:pycharm、Chrome編程
工具包:requests,lxml, remarkdown
先對目標網址發送網絡請求,《import requests 》工具包是要下載的哈,最好是在pycharm裏面下載。點擊工具欄以下圖:網絡
而後在輸入pip install 就是下載別的命令的,以下圖:工具
而後在熱搜的空白界面鼠標右鍵點擊彈出的選項查看源代碼,能夠發現標題,在獲取到網頁數據,提取到標題數據以下圖:oop
獲取了網頁數據,咱們就要經過xpath提取對應圖片地址post
獲取詳情內容地址,詳情地址並不在a標籤內哦,咱們要用正則提取詳情頁面地址:學習
詳情url須要進行分割替換,獲取準確的url地址
import re # 正則表達式
import requests # 發送網絡請求
from lxml import etree # 轉換數據的
# 贊成資源定位符
url = 'https://www.zhihu.com/billboard'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0',
}
# 發送網絡請求
response = requests.get(url, headers=headers)
# print(response.text)
# 提取數據 xpath方式 提取數據 正則 bs4
new_url_list = re.findall('link":{"url":"(.*?)"}', response.text)
print(new_url_list)
html_object = etree.HTML(response.text)
a_list = html_object.xpath('//a[@class="HotList-item"]')
# print(a_list)
for a, new_url in zip(a_list, new_url_list):
title = a.xpath('.//div[@class="HotList-itemBody"]/div[1]/text()')[0]
url1 = new_url.replace('u002F', '')
img_url = a.xpath('./div[@class="HotList-itemImgContainer"]/img/@src')[0]
f = open('知乎熱榜數據.text', "a", encoding='utf-8')
f.write("標題:" + title + '\n')
f.write("文章地址:" + url1 + '\n')
f.write("圖片地址:" + img_url + "\n")
f.write("\n")
複製代碼
我是白又白i,一名喜歡分享知識的程序媛❤️
若是沒有接觸過編程這塊的朋友看到這篇博客,發現不會的或者想要學習Python的,能夠直接留言或者私我【很是感謝你的點贊、收藏、關注、評論,一鍵四連支持】