訪問最初選擇的標記的內部標記及其屬性

讓我們假設你在選擇 soup.find('div', class_='base class') 之後得到了一個 html

from bs4 import BeautifulSoup

soup = BeautifulSoup(SomePage, 'lxml')
html = soup.find('div', class_='base class')
print(html)

<div class="base class">
  <div>Sample text 1</div>
  <div>Sample text 2</div>
  <div>
    <a class="ordinary link" href="https://example.com">URL text</a>
  </div>
</div>

<div class="Confusing class"></div>
'''

如果你想訪問 <a> 標籤的 href,你可以這樣做:

a_tag = html.a
link = a_tag['href']
print(link)

https://example.com

當你無法直接選擇 <a> 標籤時,這很有用,因為它的 attrs 沒有給你唯一的標識,在解析的頁面中還有其他 twin``<a> 標籤。但你可以唯一地選擇包含所需 <a> 的父標籤。