htmlDoc = """
<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" id="link1">Elsie</a>,
<a class="sister" id="link2">Lacie</a> and
<a class="sister" id="link3">Tillie</a>;and they lived at the bottom of a well.</p>
<p class="story">...</p>"""
調(diào)用庫
from bs4 import BeautifulSoup #Python3
soup = BeautifulSoup(htmlDoc)
查找元素
下面每行代碼都是等價的方法植康,返回結(jié)果也都一樣
ps1 = soup('p') //返回所有<p></p>
ps2 = soup.find_all('p')
結(jié)構(gòu)化輸出
1.僅獲取文本
print(soup.get_text())
# The Dormouse's story
#
# The Dormouse's story
#
# Once upon a time there were three little sisters; and their names were
# Elsie,
# Lacie and
# Tillie;# and they lived at the bottom of a well.
#
# ...
1. href
for link in soup.find_all('a'):
print(link.get('href'))
# http://example.com/elsie
# http://example.com/lacie
# http://example.com/tillie