官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/
# coding:utf-8
from bs4 import BeautifulSoup
import re
html_doc = '''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, 'html.parser', from_encoding='utf-8')
print '1.获取所有A标签'
links = soup.find_all('a') # 注意,是find_all非findAll
for item in links:
print '标签名:', item.name, '链接:', item['href'], '标签内容:', item.get_text()
print '-----------------------------------------------------------------------------------'
#
print '2.获取lacie的链接'
link_node = soup.find('a', href='http://example.com/lacie')
print '标签名:', link_node.name, '链接:', link_node['href'], '标签内容:', link_node.get_text()
print '-----------------------------------------------------------------------------------'
#
print '3.正则匹配illi'
link_node1 = soup.find('a', href=re.compile(r'illi'))
print '标签名:', link_node1.name, '链接:', link_node1['href'], '标签内容:', link_node1.get_text()
print '-----------------------------------------------------------------------------------'
#
print '4.获取P标签class="story"下面的文字'
link_node2 = soup.find('p', class_="title") # 注意class_非class
print '标签名:', link_node2.name, '标签内容:', link_node2.get_text()
浙公网安备 33010602011771号