python reptile(爬蟲)[一]

使用request獲取網頁資源

#導入
import requests
from bs4 import BeautifulSoup
# 獲取
res = requests.get("https://www.sina.com.cn/")
#指定編碼
res.encoding = "utf-8"

使用beautifulsoup獲取指定資源

# 轉化request對應爲soup , 並指定html解釋器
soup = BeautifulSoup(res.text,"html.parser")
# 獲取指定id內容--: 以#開頭
for news in soup.select("#ad_45976"):
    print(news.text)
# 獲取指定html標籤內容 直接使用標籤名
for news in soup.select("a"):
    print(news.text)
# 獲取指定class內容 --: 以.開頭
soup.select(".top-nav")[0].text  # 獲得目標class的內容
# 組合查詢 子級
print(soup.select(".top-nav .tn-title")[0].text) # 在class top-nav下的 class tn-title的內容 
# 組合查詢 屬性
print(soup.select('a[target="_blank"]')) #target屬性爲_blank的a標籤
# 自核查詢 直接子標籤
print(soup.select("i > em"))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章