一、根据下载好的HTML网页字符串创建一个BeautifulSoup的对象,创建的同时是将整个文档加载成一个DOM树; 二、根据这个DOM树就可以按照节点的名称、属性和文字搜索节点:find_all()方法会搜索出所有满足要求的节点,find()方法只会搜索出第一个满足要求的节点;两个方法的参数一模一样; 三、得到节点以后,就可以访问它的名称、属性、文字。
<a href='123.html' class='article_link'>python</a>
#a为标签名称(超链接),href,class为属性,显示在页面上的是python
In [6]: soup.find_all('a')#查找所有标签为a的节点
Out[6]:
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
In [20]: link[1]['href'] #查找a节点的href属性
Out[20]: u'http://example.com/lacie'
In [21]: link[1].get_text()#查找a节点链接文字
Out[21]: u'Lacie'
In [22]: link[0].get_text()
Out[22]: u'Elsie'
In [24]: link[1].name#查找a节点标签的名称
Out[24]: u'a'
soup=BeautifulSoup(html_doc,'html.parser',from_encoding='utf-8')#第一个参数为文档,第二个参数为解析器,第三个参数为编码
In [28]: links=soup.find_all('a')
In [30]: for i in links:
print i.name,i['href'],i.get_text()
....:
a http://example.com/elsie Elsie
a http://example.com/lacie Lacie
a http://example.com/tillie Tillie
In [34]: link_node=soup.find('a',href=re.compile(r'els'))#使用正则表达式匹配
In [39]: In [35]: print link_node.name,link_node['href'],link_node.get_text()
a http://example.com/elsie Elsie
In [5]: from bs4 import BeautifulSoup
In [6]: 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>
...: """
In [8]: soup=BeautifulSoup(html_doc)
In [9]: print(soup.prettify)
<bound method BeautifulSoup.prettify of <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 class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
</body></html>>
In [12]: p_node=soup.find('p',class_='title')
In [13]: p_node.name
Out[13]: u'p'
In [15]: print p_node['class']
[u'title']
In [16]: print p_node.get_text
<bound method Tag.get_text of <p class="title"><b>The Dormouse's story</b></p>>
In [17]: print p_node.get_text()
The Dormouse's story