Python出现“self.attrs[key]]错误

2024-10-01 00:22:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始学习在python上编写一些复杂的代码,今天我决定使用BeautifulSoup。当我尝试获取产品名称时,出现了问题,我尝试将“.find”更改为“.findAll”,但找不到解决方案。有人请帮帮我。 这是我的密码:

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as Soup
ListaSteam = "https://store.steampowered.com/search/?sort_by=Price_ASC&category1=998%2C996&category2=29"

#PAGINA - OBTENCION - CERRADA
Pagina = uReq(ListaSteam)
PaginaHtml = Pagina.read()
Pagina.close()

#1 PASO
PaginaSoup = Soup(PaginaHtml, "html.parser")
CodigoJuegos = PaginaSoup.find("div",{"id":"search_resultsRows"})
PRUEBA = CodigoJuegos.a.span["title"]
print(PRUEBA)

错误如下:

This is the error:
    `Traceback (most recent call last):
  File "C:\Users\Usuario\Desktop\******", line 14, in <module>
    PRUEBA = CodigoJuegos.a.span["title"]
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\bs4\element.py", line 1406, in __getitem__
    return self.attrs[key]
KeyError: 'title'

Tags: fromimportsearchtitleasfindpruebasoup
3条回答

可能是您想要做的:

PRUEBA = CodigoJuegos.a.get_text("title")

使用css选择器'spna.title'

CodigoJuegos = PaginaSoup.select('span.title')
for t in CodigoJuegos:
    print(t.text)

首先,您应该使用PEP8 styling。很难读懂你的代码

如果要以最少的代码更改量解决此问题,请执行以下操作:

PRUEBA = CodigoJuegos.a.span.text

这就是说,我专业地使用bs4(以及其他工具)浏览网站,我会选择这样的方式:

import requests
from bs4 import BeautifulSoup

search_url = "https://store.steampowered.com/search"
category1 = ('998', '996')
category2 = '29'

params = {
    'sort_by': 'Price_ASC',
    'category1': ','.join(category1),
    'category2': category2,
}

response = requests.get(
    search_url,
    params=params
)

soup = BeautifulSoup(response.text, "html.parser")
elms = soup.find_all("span", {"class": "title"})

for elm in elms: 
    print(elm.text)

输出:

Barro F
The Last Hope: Trump vs Mafia - North Korea
Ninja Stealth
Tetropunk
Oracle
Legend of Himari
Planes, Bullets and Vodka
Shift
Blast-off
...

如果您已经对bs4有依赖关系,那么还可以获得requests

相关问题 更多 >