使用BeautifulSoup

下载bs4,导入BeautifulSoup

pip install bs4

from bs4 import BeautifulSoup

BeautifulSoup 的使用

  1. 创建对象
r = requests.get(url)
sp = BeautifulSoup(r.text,"html.parser")

2、属性参考

属性或方法 说明
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')

3、抓取属性内容
get(属性名称)

data1 = sp.find('a',{'id':'link1'})
print(data1.get('href'))  #返回href的值

例如:

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)
posted @ 2018-10-05 18:06  我和僵尸有个约会  阅读(138)  评论(0编辑  收藏  举报