爬虫之获取标签内部信息

find_all,以及find属性:

find_all属性是把获取下来的文本中进行查找;
找到所有的相关属性;


find属性是将查找的第一个相关属性就停止了


例如
find.all('a')['href']表示的是获取文本中a标签   并从a标签下获取href这个属性;
find.all('a').get_text() 表示的是获取a标签的内容

代码演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from bs4 import BeautifulSoup
import re
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,'lxml',from_encoding="utf-8")
links=soup.find_all('a')
for link in links:
print(link.name,link['href'],link.get_text())
link_node=soup.find('a',href=re.compile(r"ill"))
print(link_node.name,link_node['href'],link_node.get_text())
p1=soup.find('p')
print(p1.name,p1.get_text())
Fork me on GitHub