【问题标题】:Webscraping with beautiful soup 4, class not workingWeb Scraping with beautiful soup 4,类不工作
【发布时间】:2021-08-22 23:30:35
【问题描述】:

我正在尝试从这个页面抓取球员数据,作为个人的经验: https://sofifa.com/players 所以我想获取在这种 HTML 行中的玩家 ID:

<td class = "col col-pi" data-col="pi"> 11111 </td>

所以我要做的是: 我先喝汤

url = 'http://sofifa.com/players'

def soup_making(url):
    my_page = requests.get(url)
    soup = bs(my_page.text, "html.parser")
    return soup


soup = soup_making(url)

我尝试用 find_all 进行 scraping

test = soup.find_all('td',{'class':'col col-pi'})
print(test)

输出是[],这个方法对同一页面的其他类都有效,但是对于这个特定的“col col-pi”以及其他一些类似“col col-name”的类,它不起作用,但如果我把这个刮掉:

<td class = "col col-ae" data-col="ae"> 26 </td>
test = soup.find_all('td',{'class':'col col-ae'})
print(test)

这行得通,当我对两者使用相同的方法时,有谁知道为什么要使用某些类而不是其他类?你推荐一个更好的方法吗?

感谢@myz540 的回答太奇怪了,没有选择所有的 td 类,这是我看到的源代码的图像: Example of the sofifa source code td classes

【问题讨论】:

    标签: python html web-scraping beautifulsoup css-selectors


    【解决方案1】:

    我去了现场并检查了源头。我复制了您的代码并抓取了所有 td 元素,但没有找到任何 class="col col-pi" 元素。

    soup = soup_making(url)
    tags = soup.find_all('td')
    all_td_classes = set()
    for tag in tags:
        for c in tag.attrs['class']:
            all_td_classes.add(c)
    
    print(all_td_classes)
    

    输出:

    {'col-oa', 'col-name', 'col-pt', 'col-vl', 'col', 'col-wg', 'col-comment', 'col-ae', 'col-tt', 'col-avatar'}
    False
    

    您在哪里看到玩家 ID?

    【讨论】:

    • 太奇怪了,没有选择所有的类:
    • 是的,你能截图你看到class的来源吗?完全没找到
    • 有趣的是,我使用的是 chrome,我看到的 td 元素似乎比你少得多。我用屏幕截图更新了我的答案。抱歉,我无法提供帮助
    • 感谢您的帮助,我知道我现在的问题是什么,如果我只使用 sofifa.com 网址,我将抓取默认属性,即您看到的那些,我必须在 URL 中指定我想要什么属性,以便我的代码抓取所需的类,因此我的 URL 必须如下所示:sofifa.com/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2019-09-20
    相关资源
    最近更新 更多