AttributeError:“set”对象在库存检查器中没有属性“items”Python产品

2024-09-27 21:34:14 发布

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

我正在尝试使用Python创建一个程序来检查产品是否有库存。如果它有库存,它应该打印-200,库存。如果不是的话,那就有200辆,缺货了

我使用的程序代码基于Arya Boudaie的代码。稍后我会设法弄清楚如何让它给我发一封电子邮件,让我知道它的库存,希望如此

我得到的错误在标题中:突出显示的部分是页面变量,表示set对象没有属性项

完全回溯是:

Exception has occurred: AttributeError 'set' object has no attribute 'items'
  File "C:\Users\Bob\Desktop\dyson2.py", line 7, in get_page_html
    page = requests.get(url, headers=headers)
  File "C:\Users\Bob\Desktop\dyson2.py", line 19, in check_inventory
    page_html = get_page_html(url)
  File "C:\Users\Bob\Desktop\dyson2.py", line 26, in <module>
    check_inventory() 

代码如下:

from bs4 import BeautifulSoup
import requests
import time

def get_page_html(URL):
    headers = {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"}
    page = requests.get(url, headers=headers)
    print(page.status_code)
    return page.content


def check_item_in_stock(page_html):
    soup = BeautifulSoup(page_html, 'html.parser')
    out_of_stock_div = soup.find("div", {"id": "sold_out_text"})
    return out_of_stock_div.text == "In stock."

def check_inventory():
    url = "https://www.boots.com/dyson-v10-cyclone-animal-10267801" 
    page_html = get_page_html(URL)
    if check_item_in_stock(page_html):
        print("In stock")
    else:
        print("Out of stock")

while True:
    check_inventory()
    time.sleep(60)

Tags: inurlgethtmlcheckstock库存page
1条回答
网友
1楼 · 发布于 2024-09-27 21:34:14

在函数get_page_html(url)中,键在headers定义中丢失,因此它变成了^{}(参见文档中的示例),但是^{}期望headers^{}(具有items()方法)

如果将其更改为以下内容,则应能正常工作:

def get_page_html(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"
#       ^^^^^^^^^^^^^
#       This is missing in your code.
    }
    page = requests.get(url, headers=headers)
    print(page.status_code)
    return page.content

(您还需要确保对变量使用相同的大写/小写拼写。在本例中,您混合了URLurl两种Python变量。)

相关问题 更多 >

    热门问题