【问题标题】:How to select tags by attribute value with Beautiful Soup如何使用 Beautiful Soup 按属性值选择标签
【发布时间】:2014-07-27 18:49:57
【问题描述】:

我有以下 HTML 片段:

>>> a
<div class="headercolumn">
<h2>
<a class="results" data-name="result-name" href="/xxy> my text</a>
</h2>

我只在属性 data-name="result-name" 时才尝试选择标题列

我试过了:

>>> a.select('a["data-name="result-name""]')

这给出了:

ValueError: Unsupported or invalid CSS selector: 

我怎样才能让它工作?

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

你可以这样做:

soup = BeautifulSoup(html)
results = soup.findAll("a", {"data-name" : "result-name"})

来源:How to find tags with only certain attributes - BeautifulSoup

【讨论】:

  • 感谢您的解释 - 比尔
【解决方案2】:
html = """
<div class="headercolumn">
<h2>
<a class="results" data-name="result-name" href="/xxy> my text</a>
</h2>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
for d in soup.findAll("div",{"class":"headercolumn"}):
    print d.a.get("data-name")
    print d.select("a.results")

result-name
[<a class="results" data-name="result-name" href="/xxy&gt; my text&lt;/a&gt;&lt;/h2&gt;"></a>]

【讨论】:

  • 谢谢 Padraic,您介意解释一下“print d.a.get("data-name")”中选择的内容吗 - Bill
  • d.a&lt;class 'bs4.element.Tag'&gt;,您像字典一样访问它,如果标签中存在data-name,它将打印"result-name" 在这种情况下的值,您可以使用d.a["data-name"] 但如果您使用 find_all 迭代不同的元素,并且如果 data-name 不存在,您将收到 keyError,使用 get 将允许检查它是否存在,如果不存在则继续。
【解决方案3】:

选择类或 ID

soup.select('a.gamers') # select an `a` tag with the class gamers
soup.select('a#gamer') # select an `a` tag with the id gamer

选择单个属性:

soup.select('a[attr="value"]')

选择多个属性:

attr_dict = {
             'attr1': 'val1',
             'attr2': 'val2',
             'attr3': 'val3'
            }

soup.findAll('a', attr_dict)

您可以在 soup.select 中使用任何 CSS 选择器

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多