Python的;self.attrs[key]]”;错误
我开始学习在python上编写一些复杂的代码,今天我决定使用BeautifulSoup。当我尝试获取产品名称时,出现了问题,我尝试将“.find”更改为“.findAll”,但找不到解决方案。有人请帮帮我。 这是我的密码:Python的;self.attrs[key]]”;错误,python,beautifulsoup,keyerror,Python,Beautifulsoup,Keyerror,我开始学习在python上编写一些复杂的代码,今天我决定使用BeautifulSoup。当我尝试获取产品名称时,出现了问题,我尝试将“.find”更改为“.findAll”,但找不到解决方案。有人请帮帮我。 这是我的密码: from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as Soup ListaSteam = "https://store.steampowered.com/search/
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'
这是错误:
`回溯(最近一次呼叫最后一次):
文件“C:\Users\Usuario\Desktop\****”,第14行,在
PRUEBA=CodigoJuegos.a.span[“标题”]
文件“C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site packages\bs4\element.py”,第1406行,在u getitem中__
返回self.attrs[键]
KeyError:“标题”
可能是您想要做的:
PRUEBA = CodigoJuegos.a.get_text("title")
首先,你应该使用。很难读懂你的代码
如果要以最少的代码更改量解决此问题,请执行以下操作:
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
,那么您也可能会收到请求。使用css选择器'spna.title'
CodigoJuegos = PaginaSoup.select('span.title')
for t in CodigoJuegos:
print(t.text)