繁体   English   中英

如何使用 BeautifulSoup 在特定 class 下获取 href 链接

[英]How do I get href links under a specific class with BeautifulSoup

这是我使用 BeautifulSoup 源代码的块类型的示例 HTML

 <div class="fighter_list left">
                            <meta itemprop="image" content="/image_crop/44/44/_images/fighter/1406924569376_20140801011731_Picture17.JPG">
                            <img class="lazy" src="/image_crop/44/44/_images/fighter/1406924569376_20140801011731_Picture17.JPG" data-original="/image_crop/44/44/_images/fighter/1406924569376_20140801011731_Picture17.JPG" alt="Jason DeLucia" title="Jason DeLucia" />
                            <div class="fighter_result_data">
                                <a itemprop="url" href="/fighter/Jason-DeLucia-22"><span itemprop="name">Jason<br />DeLucia</span></a><br>

对于页面上的每个“fighter_list left”,这是这样的多个块之一。

我想获取“fighter_list left”class 中的所有 itemprop="url" href 链接(即 /fighter/Jason-DeLucia-22)

当我尝试下面的代码时,我什么也没得到。

for link in html.find_all('a', class_="fighter_List left", itemprop="url"):
    print(link.get('href'))

当我省略 class_= 部分时,我能得到的最接近的是获取页面上的每个 itemprop=url 链接。 但我只想要 fighter_list 下的那些离开 class。

这是网站https://www.sherdog.com/events/UFC-1-The-Beginning-7

您可以为任务使用 CSS 选择器:

import requests
from bs4 import BeautifulSoup

url = "https://www.sherdog.com/events/UFC-1-The-Beginning-7"

soup = BeautifulSoup(requests.get(url).content, "html.parser")

for link in soup.select('.fighter_list.left [itemprop="url"]'):
    print(link["href"])

印刷:

/fighter/Jason-DeLucia-22
/fighter/Royce-Gracie-19
/fighter/Gerard-Gordeau-15
/fighter/Ken-Shamrock-4
/fighter/Royce-Gracie-19
/fighter/Kevin-Rosier-17
/fighter/Gerard-Gordeau-15

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM