使用BeautifulSoup

下载bs4,导入BeautifulSoup

pip install bs4html

from bs4 import BeautifulSoup

BeautifulSoup 的使用

  1. 建立对象
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)
相关文章
相关标签/搜索