Python 有"self.attrs[key]]"错误



我开始在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:UsersUsuarioDesktop******", line 14, in <module>
PRUEBA = CodigoJuegos.a.span["title"]
File "C:UsersUsuarioAppDataLocalProgramsPythonPython39libsite-packagesbs4element.py", line 1406, in __getitem__
return self.attrs[key]
KeyError: 'title'

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

如果你想用最少的代码修改来解决这个问题,请执行以下操作:

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

可能是你想做的:

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

using css selector'spna.title'

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

最新更新