Selenium學習筆記||3、BeautifulSoup

1、 Beautiful Soup是啥

  Beautiful Soup是能夠從html文件中提取數據的庫。html

  官網連接:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/index.html#html5

  能夠從父子點的html獲取回來,利用Beautiful Soup在本地分析spa

 

2、Beautiful Soup安裝

  pip install beautifulsoup4code

  pip install html5libhtm

 

3、一個簡單的例子

# -*- 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

 

4、find_all

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

5、find_all能夠根據屬性縮小範圍

# -*- 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)

6、按子節點查找

# -*- 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)

 

 

7、按父節點查找

# -*- 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)

 

相關文章
相關標籤/搜索