Gromil
Gromil

Reputation: 63

Beautiful Soup find element with multiple classes

<div data-list="1" data-href="/a/ajaxPhones?id=46420863" class="action-link 
showPhonesLink">Показать телефон</div>

How do I find the above element in Beautiful Soup?

I've tried the following, but it didn't work:

show = soup.find('div', {'class': 'action-link showPhonesLink'})

How can I get that element?

Upvotes: 5

Views: 9412

Answers (2)

Marco Bonelli
Marco Bonelli

Reputation: 69276

Use a selector:

show = soup.select_one('div.action-link.showPhonesLink')

Or match the exact class attribute:

show = soup.find('div', class_='action-link showPhonesLink')

# or (for older versions of BeautifulSoup)
show = soup.find('div', attr={'class': 'action-link showPhonesLink'})

Note that with the second method the order of the classes is important, as well as the whitespace, since it is an exact match on the class attribute. If anything changes in the class attribute (e.g. one more space between the classes) it will not match.

I would suggest the first method.

Upvotes: 5

john smith
john smith

Reputation: 50

I'm guessing the soup in show = soup.find() is

source = requests.get(URL to get).text
soup = BeautifulSoup(source, 'lxml')

try:

show = soup.find('div', class_='action-link showPhonesLink').text

.text doesn't always work, but I've found the result doesn't really change without it.

i could give a more help answer if you could provide a little more details.

Upvotes: 0

Related Questions