f ff
f ff

Reputation: 47

Beautiful soup find_all doesn't find CSS selector with multiple classes

On the website there is this <a> element

<a role="listitem" aria-level="1" href="https://www.rest.co.il" target="_blank" class="icon rest" title="this is main title" iconwidth="35px" aria-label="website connection" style="width: 30px; overflow: hidden;"></a>

So I use this code to catch the element
(note the find_all argument a.icon.rest)

import requests
from bs4 import BeautifulSoup

url = 'http://www.zap.co.il/models.aspx?sog=e-cellphone&pageinfo=1'
source_code = requests.get(url)
plain_text = source_code.text
soup  = BeautifulSoup(plain_text, "html.parser")
for link in soup.find_all("a.icon.rest"):
    x = link.get('href')
    print(x)

Which unfortunately returns nothing
although the beautiful soup documentation clearly says:

If you want to search for tags that match two or more CSS classes, you should use a CSS selector:

css_soup.select("p.strikeout.body")
returns: <p class="body strikeout"></p>

So why isn't this working? By the way, I'm using pycharm

Upvotes: 1

Views: 1129

Answers (1)

abarnert
abarnert

Reputation: 365747

As the docs you quoted explain, if you want to search for tags that match two CSS classes, you have to use a CSS selector instead of a find_all. The example you quoted shows how to do that:

css_soup.select("p.strikeout.body")

But you didn't do that; you used find_all anyway, and of course it didn't work, because find_all doesn't take a CSS selector.

Change it to use select, which does take a CSS selector, and it will work.

Upvotes: 1

Related Questions