分享一下关于 Python的网页解析器(BeautifulSoup)
BeautifulSoup解析器
为了实现解析器,可以选择使用正则表达式、html.parser、BeautifulSoup、lxml等,所以BeautifulSoup是比较好的选择。
其中,正则表达式基于模糊匹配,而另外三种则是基于DOM结构化解析。
安装测试
1、安装,在命令行下执行pip install beautifulsoup4
。
2、测试
import bs4 print(bs4)
使用说明
基本用法
1、创建BeautifulSoup对象
import bs4 from bs4 import BeautifulSoup # 根据html网页字符串创建BeautifulSoup对象 html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ 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、从文档中找到所有<a>
标签的链接
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)