【发布时间】:2021-02-01 13:04:16
【问题描述】:
我正在创建一个 Python 程序,该程序使用网络抓取来检查商品是否有货。该代码是 Python 3.9 脚本,使用 Beautiful Soup 4 并请求抓取该项目的可用性。我最终想让程序搜索多个网站和每个网站内的多个链接,这样我就不必一次运行一堆脚本。程序的预期结果是这样的:2000In Stock
但我得到了:200[]Out Of Stock
'200'表示代码是否可以访问服务器,200是预期结果。 “0”是一个布尔值,用于查看该项目是否有库存,预期的响应是“0”表示有货。我已经给它提供了库存商品和缺货商品,它们都给出了相同的回复200 [] Out Of Stock。我感觉def check_item_in_stock 中的out_of_stock_divs 有问题,因为这是我得到[] 的结果,因为它找到了该项目的可用性
昨天早些时候我的代码可以正常工作,但我一直在添加功能(比如它抓取多个链接和不同的网站),结果破坏了它,我无法让它恢复到工作状态
这是程序代码。 (我确实将此代码基于 Arya Boudaie 先生在他的网站上的代码,https://aryaboudaie.com/ 我摆脱了他的文本通知,因为我打算只在我旁边的备用计算机上运行它并让它播放响亮的声音,这将在以后实施。)
from bs4 import BeautifulSoup
import requests
def get_page_html(url):
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 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_divs = soup.findAll("text", {"class": "product-inventory"})
print(out_of_stock_divs)
return len(out_of_stock_divs) != 0
def check_inventory():
url = "https://www.newegg.com/hp-prodesk-400-g5-nettop-computer/p/N82E16883997492?Item=9SIA7ABC996974"
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)```
【问题讨论】:
标签: python python-3.x web-scraping beautifulsoup