pip install bs4html
from bs4 import BeautifulSoup
r = requests.get(url) sp = BeautifulSoup(r.text,"html.parser")
二、屬性參考
屬性或方法 | 說明
--- | ---
title | 返回網頁的標題
text | 返回去除全部HTML標籤後的網頁內容
find() | 返回第一個符合條件的標籤。例如:sp.find('a')
find_all() | 返回全部符合條件的標籤。 例如:sp.find_all('a')
select() | 若是參數爲標籤名,返回結果與find_all()方法相同。除了用標籤名做爲參數外,本方法還可使用CSS樣式表(id屬性或class屬性)做爲參數。例如:sp.select('#id'), sp.select('.class')python
三、抓取屬性內容
get(屬性名稱)url
data1 = sp.find('a',{'id':'link1'}) print(data1.get('href')) #返回href的值
例如:code
import requests from bs4 import BeautifulSoup url = "http://www.pm25x.com/" r = requests.get(url=url) #print(r.text) b = BeautifulSoup(r.text, "html.parser") city = b.find("a", {"title": "北京PM2.5"}) href = city.get("href") url2 = url + href #print(href) r2 = requests.get(url=url2) sp = BeautifulSoup(r2.text, "html.parser") data1 = sp.select(".aqivalue") print(data1) pm25 = data1[0].text print(pm25)