代码之家  ›  专栏  ›  技术社区  ›  DevinGP

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

  •  0
  • DevinGP  · 技术社区  · 6 年前
    <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本身并不太熟悉,也没有遇到过一个href也有一个类和 data-pet-card="pet-card-link"

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

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

    2 回复  |  直到 6 年前
        1
  •  4
  •   Daniel Roseman    6 年前

    您在 find_all 电话是你拥有的东西,而不是你想找到的东西。这是你的课程,所以使用:

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

    (因为 class 是Python中的保留字,需要使用 class_ 在这里。)

        2
  •  0
  •   yogkm    6 年前
    for a in soup.find_all('a', href=True):
        print("Found the URL:", a.get_attribute_list('href')[0])
    

    请尝试这个解决方案。