【问题标题】:Beautiful Soup strangely returning '/photo-missing.png'美丽的汤奇怪地返回'/photo-missing.png'
【发布时间】:2023-03-27 01:42:01
【问题描述】:

我正在尝试自动从 www.premierleague.com 网站下载球员图片。我现在面临的问题是,当我使用 BeautifulSoup 解析玩家照片的 img src 时,它返回“photo-missing.png”。

当您检查 html 时可以看到它被称为 p51490.png !?而不是“photo-missing.png”

我的代码如下:

import requests
from bs4 import BeautifulSoup

player_page = requests.get('https://www.premierleague.com/players/4330/David-De-Gea/overview')
soup = BeautifulSoup(player_page.text, 'html.parser')
print(soup.find(class_="imgContainer"))

这个产生的输出:

 <div class="imgContainer"><img alt="David De Gea" class="img" data- 
    player="p51940" data-script="pl_player-image" data-size="250x250" data- 
    widget="player-image" src="//platform-static- 
    files.s3.amazonaws.com/premierleague/photos/players/250x250/Photo- 
    Missing.png"/></div>

我想知道是否有人知道为什么会这样?

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup


    【解决方案1】:

    它是由JS自动生成的,可能是为了防止刮擦。但是您可以将Photo-Missing 替换为p51490,此值保存在data-player 属性中。

    soup = BeautifulSoup(player_page.text, 'html.parser')
    # using CSS selector
    img = soup.select_one('.imgContainer img')
    img['src'] = img['src'].replace('Photo-Missing', img['data-player'])
    print(img)
    print(img['src'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      相关资源
      最近更新 更多