首页 > 解决方案 > 得到一个 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)

标签: pythonbeautifulsouppython-telegram-bot

解决方案


您的问题可能是由于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']

推荐阅读