[Python] 纯文本查看 复制代码
from bs4 import BeautifulSoup
html = '''<html>
<body>
<h1>我的网站</h1>
<p>这是我的网站</p>
<body>
</html>''' #从网页拿到html的格式化的字符串,保存到html里
soup = BeautifulSoup(html, 'lxml') #使用lxml解析器来解析文本,html和xml格式是类似的
print(soup.find_all('h1')) #使用find_all函数来找所有的h1标签,返回的结果是数组
print(soup.find_all('p')) #找所有的p标签,返回的结果是数组
更复杂一点的,比如
from bs4 import BeautifulSoup
html = '''<html>
<body>
<h1>我的网站</h1>
<p>这是我的网站</p>
<div class='test-item'>
测试1
</div>
<div class='test-item'>
测试2
</div>
<body>
</html>'''
soup = BeautifulSoup(html, 'lxml')
div_tags = soup.find_all(name='div', attrs={'class': 'test-item'})
for tag in div_tags:
print(type(tag))
print(tag)
print(tag.string)
print(tag.attrs, '\n')