python - 得到一个 keyerror '项目'
问题描述
我遇到了 BeautifulSoup 的问题
Traceback (most recent call last):
File "C:\Users\Милена\Documents\html\pricetracker bot\main.py", line 24, in <module>
price=soup.select_one('div[class="current-price"]')['item']
File "C:\Users\Милена\AppData\Local\Programs\Python\Python39\lib\site-packages\bs4\element.py", line 1406, in __getitem__
return self.attrs[key]
KeyError: 'item'
我对 python 和电报机器人完全陌生,所以我不知道我有什么问题。我在下面的代码或 div 本身中犯了错误吗?
from dotenv import load_dotenv
load_dotenv()
import os
import requests
from bs4 import BeautifulSoup
BASE_URL='https://www.sulpak.kz/'
TOKEN=os.getenv('TOKEN')
CHAT_ID=os.getenv('CHAT_ID')
TELEGRAM_API_SEND_MSG=f'https://api.telegram.org/bot{TOKEN}/sendMessage'
items = [
'g/noutbuk_asus_zenbook_um431da_am020t_r785uw_90nb0pb3_m01810_62_1747',
'g/smartfon_samsung__galaxy_note20_gray_sm_n980fzagskz_77_2514'
]
for item in items:
url=BASE_URL + item
r = requests.get(url)
soup=BeautifulSoup(r.text, 'html.parser')
name = soup.select_one('h1[class="product-container-title"]').get_text()
price=soup.select_one('div[class="current-price"]')['item']
data = {
'chat_id': CHAT_ID,
'text': f'*${price}*\n[{name}]({url})',
'parse_mode': 'Markdown'
}
r = requests.post(TELEGRAM_API_SEND_MSG, data=data)
解决方案
您的问题可能是由于soup.select_one('div[class="current-price"]')
未返回包含带有 key 的项目的对象item
。因此,当您应用['item']
该返回值时,您会收到该错误。我建议您将值分配给soup.select_one('div[class="current-price"]')
变量,然后首先检查它是否包含 key item
,然后在不包含的情况下执行任何适当的操作。例如:
priceDiv=soup.select_one('div[class="current-price"]')
if 'item' not in priceDiv:
... do here whatever is appropriate when `item` is not found ...
price = priceDiv['item']
推荐阅读
- logstash - logstash 将 ruby 代码转换为 logstash 过滤器
- python - Plotly-Dash:如何仅更新图形数据而不更改图形布局?
- pandas - 如何将表格数据(Pandas Dataframe)重塑为 RNN 的 3D 数据?
- reactjs - React.js - TypeError:college.map 不是函数
- python - 根据不同的行和列拆分行
- python - 可以在 django 中删除对象的特定行吗?
- python - 列表的随机值
- javascript - 列表中的 javascript link() 方法输出
- r - 如何将csv文件更改为栅格?
- python - 慢棋机器人,需要走得更快