怎么使用BeautifulSoup解析HTML文檔

小億
104
2024-05-14 10:53:11

使用BeautifulSoup解析HTML文檔的基本步驟如下:

  1. 導(dǎo)入BeautifulSoup庫(kù):
from bs4 import BeautifulSoup
  1. 創(chuàng)建BeautifulSoup對(duì)象并傳入HTML文檔和解析器:
html_doc = """
<html>
<head>
<title>Example HTML Document</title>
</head>
<body>
<p>This is an example paragraph.</p>
</body>
</html>
"""

soup = BeautifulSoup(html_doc, 'html.parser')
  1. 使用BeautifulSoup對(duì)象查找和提取需要的信息:
# 獲取文檔標(biāo)題
title = soup.title
print(title.text)

# 獲取第一個(gè)段落
paragraph = soup.p
print(paragraph.text)
  1. 使用BeautifulSoup對(duì)象查找特定標(biāo)簽或?qū)傩缘膬?nèi)容:
# 查找所有的段落標(biāo)簽
paragraphs = soup.find_all('p')
for p in paragraphs:
    print(p.text)

# 查找包含特定class屬性的標(biāo)簽
div = soup.find('div', class_='example_class')
print(div.text)

以上是使用BeautifulSoup解析HTML文檔的基本方法,可以根據(jù)具體的需求和HTML文檔結(jié)構(gòu)來(lái)進(jìn)一步應(yīng)用BeautifulSoup的功能。

0