DAY04
一. BeautifulSoup的使用
- BeautifulSoup4:简称bs4
- 作用:能够在html或者xml文档中查找选择所需内容
- bs4是python实现的模块
from bs4 import BeautifulSoup
- BeautifulSoup(参数1, 参数2)
参数1:前端页面的字符串类型源码。 参数2:四种解析器
# 对页面源码使用BeautifulSoup解析 --> 解析后的类型是bs
# soup = BeautifulSoup(html, "html.parser")
soup = BeautifulSoup(html, "lxml")
print(soup, type(soup))
-
select: 根据CSS选择器查找内容,select获取页面中所有符合CSS选择器的结果,存入到列表中
-
select_one:根据CSS选择器查找内容,select_one得到的结果是select结果的第一个元素,存入到列表中
-
prettify:格式化BeautifulSoup解析后的源码
注意:select得到的列表中的每个元素和select_one得到的结果一定是bs4类型
print(soup.prettify())
p_list = soup.select('p')
print(p_list)
print(type(p_list[-1])) # <class 'bs4.element.Tag'>
p = soup.select_one('p')
print(p)
- text:获取html标签(双标签)内的文本 例如:<p>abc</p> -> abc
- attrs:获取html标签内的属性值.例如:
</> -> https://www.baidu.com
b = soup.select_one('p.title > b').text
print(b, type(b))
href1 = soup.select_one('p.story > a#link3').attrs['href']
print(href1, type(href1)) # http://example.com/tillie <class 'str'>