溫馨提示×

怎么使用BeautifulSoup遍歷DOM樹

小億
102
2024-05-14 11:07:20
欄目: 編程語言

要使用BeautifulSoup遍歷DOM樹,首先需要導入BeautifulSoup庫和requests庫。

from bs4 import BeautifulSoup
import requests

然后,使用requests庫發送一個HTTP請求獲取網頁內容,并將其傳遞給BeautifulSoup解析。

url = 'http://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

接下來,可以使用BeautifulSoup提供的方法來遍歷DOM樹。比如,可以使用find()方法查找指定的標簽,使用find_all()方法查找所有符合條件的標簽,使用children屬性遍歷子節點,使用descendants屬性遍歷所有子孫節點等。

# 查找所有<a>標簽
for link in soup.find_all('a'):
    print(link.get('href'))

# 遍歷子節點
for child in soup.body.children:
    print(child)

# 遍歷所有子孫節點
for descendant in soup.descendants:
    print(descendant)

通過以上方法,可以方便地遍歷DOM樹,并提取需要的信息。需要注意的是,BeautifulSoup提供了多種方法來遍歷DOM樹,可以根據具體需求選擇合適的方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女