本章介紹怎麼根據id與class查找標籤。假設有下面的HTML文檔:
<code>
<title>A simple example page/<title>
First paragraph.
Second paragraph.
First outer paragraph.
Second outer paragraph.
/<code>
複製
可以通過URL https://kevinhwu.github.io/demo/python-scraping/simple2.html 訪問上面的文檔。讓我們先下載頁面並創建一個BeautifulSoup對象:
<code>import requests
from bs4 import BeautifulSoup
page = requests.get("https://kevinhwu.github.io/demo/python-scraping/simple2.html")
soup = BeautifulSoup(page.content, 'html.parser')
/<code>
複製
根據class查找標籤
根據id與class查找標籤,使用的仍舊是find_all方法。下面的例子,查找類是outer-text的p標籤:
<code>soup.find_all('p', class_='outer-text')
/<code>
複製
<code>[,
First outer paragraph.]
Second outer paragraph.
/<code>
複製
在下面的例子中,查找任何類是outer-text的標籤:
<code>soup.find_all(class_="outer-text")
/<code>
複製
<code>[,
First outer paragraph.]
Second outer paragraph.
/<code>
複製
根據id查找標籤
另外,也可以通過id查找標籤:
<code>soup.find_all(id="first")
/<code>
複製
<code>[]/<code>
First paragraph.
閱讀更多 見血飛程序人生 的文章