分享一下关于 Python的网页解析器(BeautifulSoup)
BeautifulSoup解析器
为了实现解析器,可以选择使用正则表达式、html.parser、BeautifulSoup、lxml等,所以BeautifulSoup是比较好的选择。
其中,正则表达式基于模糊匹配,而另外三种则是基于DOM结构化解析。
安装测试
1、安装,在命令行下执行pip install beautifulsoup4。
2、测试
importbs4print(bs4)
使用说明
基本用法
1、创建BeautifulSoup对象
import bs4
from bs4 import BeautifulSoup
# 根据html网页字符串创建BeautifulSoup对象
html_doc = """
The Dormouse's storyThe Dormouse's story
Once upon a time there were three little sisters; and their names were
Lacie and
and they lived at the bottom of a well.
...
"""
soup = BeautifulSoup(html_doc)
print(soup.prettify())
2、访问节点
print(soup.title)
print(soup.title.name)
print(soup.title.string)
print(soup.title.parent.name)
print(soup.p)
print(soup.p['class'])
3、指定tag、class或id
print(soup.find_all('a'))
print(soup.find('a'))
print(soup.find(class_='title'))
print(soup.find(id="link3"))
print(soup.find('p',class_='title'))
4、从文档中找到所有标签的链接
for link in soup.find_all('a'):
print(link.get('href'))
出现了警告,根据提示,我们在创建BeautifulSoup对象时,指定解析器即可。
soup = BeautifulSoup(html_doc,'html.parser')
5、从文档中获取所有文字内容
print(soup.get_text())
6、正则匹配
link_node = soup.find('a',href=re.compile(r"til"))
print(link_node)