簡體   English   中英

Python Beautifulsoup 訪問標簽中的屬性

[英]Python Beautifulsoup accessing attribute in tag

我正在使用 whitehouse.gov 練習抓取 web 數據。 我有

    for a_tag in soup.select('span a'):
        categories.append(a_tag)

這給了我下面的標簽......

<a href="https://www.whitehouse.gov/briefing-room/./statements-releases/" rel="category tag">Statements and Releases</a> 

現在我只想訪問“聲明和發布”,所以我想我會這樣做

   for a_tag in soup.select('span a'):
        categories.append(a_tag.attrs['rel')]

但這給了我 ['category', 'tag'] 作為 output。 我玩了一會兒,然后想通了

    for a_tag in soup.select('span a'):
        for x in a_tag: 
            categories.append(x)

給我 output 我正在尋找(聲明和發布等),但我不知道為什么?

要在 href 中獲取文本,您應該使用 text 變量:

for a_tag in soup.select('span a'):
        categories.append(a_tag.text)

或者

for a_tag in soup.select('span a'):
        categories.append(a_tag.string)

我懷疑這是你需要的:

   for a_tag in soup.select('span a'):
        categories.append(a.getText())

如果你想要Statements and Releases

鑒於,這樣做:

for a_tag in soup.select('span a'):
        categories.append(a_tag.attrs['rel'])

生成rel屬性的值,即category tag

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM