Search code examples
pythonbeautifulsoupwebdriver

python beatifull soup, find only exact class matches


hello so i have this little script

html = driver.execute_script("return document.getElementsByTagName('html')[0].innerHTML")
parse = BeautifulSoup(html, 'html.parser')
selector = Selector(text=html)
divs = selector.css('.panel .panel-heading a::attr(href)').getall()

and it works fine but i if div has

<div class="panel grey">

i dont want this to match, only exact matches when div has one div match only this

<div class="panel">

i tried using decompsoe() function but didnt worked in my case, what is the best solution i have my script done this is the only issue

so in short, find children of div only if div has one class


Solution

  • To strictly match div with class equals to panel value, not just some element that contains panel class attribute you can write that explicitly.
    Instead of

    divs = selector.css('.panel .panel-heading a::attr(href)').getall()
    

    try using

    divs = selector.css('div[class="panel"] .panel-heading a::attr(href)').getall()