简体   繁体   中英

How to select tags by attribute value with Beautiful Soup

I have the following HTML fragment:

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

I am trying to select header column only if attribute data-name="result-name"

I've tried:

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

This gives:

ValueError: Unsupported or invalid CSS selector: 

How can I get this working?

You can simply do this :

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

Source : How to find tags with only certain attributes - BeautifulSoup

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>]

select classes or ids

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

select single attr:

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

select multiple attr:

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

soup.findAll('a', attr_dict)

you can use any CSS selector in soup.select

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM