Beautiful Soup是能夠從html文件中提取數據的庫。html
官網連接:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/index.html#html5
能夠從父子點的html獲取回來,利用Beautiful Soup在本地分析spa
pip install beautifulsoup4code
pip install html5libhtm
# -*- coding: utf-8 -*-
html_doc = '''
<!DOCTYPE html>
<html>
<head>
<title>這是個標題</title>
<a href = "http://baidu.com">
</head>
<body>
<h1>這是一個一個簡單的HTML</h1>
<a href = "http://sina.com">
<p>Hello World!</p>
</body>
</html>
'''#1. 這是一段html代碼,也能夠從文件中讀取
from bs4 import BeautifulSoup#2.引入
soup = BeautifulSoup(html_doc,"html5lib")#3.選擇文件和html5lib
tag = soup.find('a')#4.尋找文件中的a標籤
print(tag)#5.打印
結果:blog
1. 返回的是列表ip
2. 查找全部結果utf-8
# -*- coding: utf-8 -*- html_doc = ''' <!DOCTYPE html> <html> <head> <title>這是個標題</title> <a href = "http://baidu.com"> </head> <body> <h1>這是一個一個簡單的HTML</h1> <a href = "http://sina.com"> <p>Hello World!</p> </body> </html> ''' from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc,"html5lib") tag = soup.find_all('a') print(tag)
結果:get
# -*- coding: utf-8 -*- html_doc = ''' <!DOCTYPE html> <html> <head> <title>這是個標題</title> <a href = "http://baidu.com"> </head> <body> <h1>這是一個一個簡單的HTML</h1> <a href = "http://sina.com" id=link1> <p>Hello World!</p> </body> </html> ''' from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc,"html5lib") tag = soup.find_all('a',id = 'link1')#這裏篩選了id爲link1屬性的內容 print(tag)
# -*- coding: utf-8 -*- html_doc = ''' <!DOCTYPE html> <html> <head> <div> <title>這是個標題</title> <a href = "http://baidu.com"> </div> </head> <body> <div> <h1>這是一個一個簡單的HTML</h1> <a href = "http://sina.com" id=link1> <p>Hello World!</p> </div> </body> </html> ''' from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc,"html5lib") tag = soup.div.a#這裏就是按照連續的子節點進行查找 print(tag)
# -*- coding: utf-8 -*- html_doc = ''' <!DOCTYPE html> <html> <head> <div> <title>這是個標題</title> <a href = "http://baidu.com"> </div> </head> <body> <div> <h1>這是一個一個簡單的HTML</h1> <p>Hello World!</p> </div> </body> </html> ''' from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc,"html5lib") tag = soup.p.parent#這裏就是查找p元素的父節點 print(tag)