Tre*_*mer 4 python beautifulsoup web-scraping python-3.x
我正在创建一个 Python 程序,它使用网络抓取来检查商品是否有库存。该代码是一个 Python 3.9 脚本,使用 Beautiful Soup 4 并请求抓取该项目的可用性。我最终想让程序搜索多个网站和每个网站内的多个链接,这样我就不必同时运行一堆脚本。该程序的预期结果是这样的:
200
0
In Stock
但我得到:
200
[]
Out Of Stock
“200”表示代码是否可以访问服务器,200 是预期结果。“0”是一个布尔值,用于查看该商品是否有库存,预期响应为“0”(表示有库存)。我给了它有库存的商品和缺货的商品,它们都给出了相同的响应200 [] Out Of Stock。out_of_stock_divs我感觉内部有问题,def check_item_in_stock因为这就是我得到的结果,[]发现该物品的可用性
昨天早些时候,我的代码工作正常,我不断添加功能(比如抓取多个链接和不同的网站),这破坏了它,我无法让它恢复到工作状态
这是程序代码。(我确实根据 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)```
Run Code Online (Sandbox Code Playgroud)
产品库存状态位于<div>标签内,而不是<text>标签内:
import requests
from bs4 import BeautifulSoup
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("div", {"class": "product-inventory"}) # <--- change "text" to div
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")
check_inventory()
Run Code Online (Sandbox Code Playgroud)
印刷:
200
[<div class="product-inventory"><strong>In stock.</strong></div>]
In stock
Run Code Online (Sandbox Code Playgroud)
注意:该网站的 HTML 标记可能在过去发生过变化,我会修改该check_item_in_stock功能:
def check_item_in_stock(page_html):
soup = BeautifulSoup(page_html, 'html.parser')
out_of_stock_div = soup.find("div", {"class": "product-inventory"})
return out_of_stock_div.text == "In stock."
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15003 次 |
| 最近记录: |