Beautiful Soup find element with multiple classes

2020-04-12 07:37发布

问题:

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

回答1:

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.



回答2:

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.