如何使用BeautifulSoup查找带有类的href链接

时间:2018-09-14 12:47:26

标签: python python-3.x parsing beautifulsoup request

<div data-pet-card="pet-card" class="pet-card">

    <a data-pet-card="pet-card-link" href="https://Link-I-Want.com" 
    class="pet-card__link">

我曾经用BS4抓取html,但是我对html本身并不十分熟悉,也没有遇到过同时具有类和data-pet-card="pet-card-link"的href。我尝试过:

for a in soup.find_all('a', href=True):
    print("Found the URL:", a['href'])

但是它什么也不打印,也没有错误。

任何事情都是有帮助的,谢谢。

1 个答案:

答案 0 :(得分:2)

您在find_all调用中添加的属性是您拥有的东西,而不是您要查找的东西。在这里,您有了课程,因此可以使用它:

for a in soup.find_all('a', class_="pet-card__link"):
    print("Found the URL:", a['href']) 

(由于class是Python中的保留字,因此您需要在此处使用class_。)