【问题标题】:Web scrapping can't grab the source of an image网络抓取无法抓取图像的来源
【发布时间】:2023-02-02 15:15:01
【问题描述】:
import requests
import bs4
res2 = requests.get("https://en.wikipedia.org/wiki/Deep_Blue_(chess_computer)")
soup = bs4.BeautifulSoup(res2.text,'lxml')
soup.select(".image")
computer = soup.select(".image")[0]
computer['class']
computer ['src']

当我运行 computer['class] 时,我得到了类名 ``但是当我运行 computer['src'] 时出现以下错误

KeyError Traceback(最后一次调用) 在 [19] 中输入 <cell line: 1>() ----> 1 台电脑['src']

文件C:\ProgramData\Anaconda3\lib\site-packages\bs4\element.py:1519,在Tag中。获取项目(自我,钥匙) 1516高清获取项目(自我,关键): 攀上漂亮女局长之后1517 1518 如果不存在则抛出异常。""" -> 1519 返回 self.attrs[key]

键错误:'src'

【问题讨论】:

  • 我想你需要 href

标签: python web-scraping


【解决方案1】:

看起来你想要参考资料.如果是这样的话:

import requests
from bs4 import BeautifulSoup as BS

(r := requests.get('https://en.wikipedia.org/wiki/Deep_Blue_(chess_computer)')).raise_for_status()
soup = BS(r.text, 'lxml')

for image in soup.select('.image'):
    if href := image.get('href'):
        print(href)

输出:

/wiki/File:Deep_Blue.jpg
/wiki/File:Chess_Programming.svg
/wiki/File:Kasparov_Magath_1985_Hamburg-2.png
/wiki/File:One_of_Deep_Blue%27s_processors_(2586060990).jpg
/wiki/File:Chess.svg
/wiki/File:Chess.svg

【讨论】:

    【解决方案2】:

    该错误是因为在元素的“attrs”字典中找不到键“src”。要访问图像的源 URL,您需要从“computer”元素中的“img”标签中提取“src”属性。试试下面的代码:computer_img = computer.select("img")[0] computer_img["src"]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 2013-09-25
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2016-10-24
      相关资源
      最近更新 更多