簡體   English   中英

如何使用 BeautifulSoup 從本網站獲取價格?

[英]How do I get the price from this website using BeautifulSoup?

所以我是用 Python 解析 HTML 的新手,我想從以下鏈接獲取這種木材的價格:

https://www.lowes.com/pd/2-in-x-4-in-x-8-ft-Whitewood-Stud-Common-1-5-in-x-3-5-in-x-實際96/1000074211

到目前為止,這是我所擁有的,但我收到一條錯誤消息:“AttributeError: 'NoneType' object has no attribute 'text'”:

import requests
from bs4 import BeautifulSoup

HEADERS = {'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, 
like Gecko) Chrome/91.0.4472.164 Safari/537.36"}

URL = "https://www.lowes.com/pd/2-in-x-4-in-x-8-ft-Whitewood-Stud-Common-1-5-in-x-3-5-in-x-96- 
in-Actual/1000074211"
r = requests.get(URL,headers=HEADERS)
c=r.content
soup = BeautifulSoup(c, "html.parser")
price_box =  soup.find("div", class_="sq-bqyKva.ehfErk")
price=price_box.text.strip()
print(price)

為什么我會收到此錯誤,我該如何解決?

我看不到該站點,但很可能您收到了錯誤,因為 BS 找不到任何具有名為“sq-bqyKva.ehfErk”的類的元素。

你能打印出湯並手動搜索該類以查看它是否確實存在嗎?

此外,根據類名,您嘗試查找的 div 似乎是使用 JavaScript 動態生成的,這意味着在發出請求時它不會加載到 DOM 中,這意味着 BS 將無法找到它。 如果是這種情況,您可能需要考慮使用其他工具,例如Selenium

該站點是動態的,依靠腳本使用來自 JSON 字符串的數據填充頁面,該字符串可以在script標記中找到並通過json模塊解析以訪問價格:

from bs4 import BeautifulSoup as soup
import json
headers = {'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36"}
d = soup(requests.get('https://www.lowes.com/pd/2-in-x-4-in-x-8-ft-Whitewood-Stud-Common-1-5-in-x-3-5-in-x-96-in-Actual/1000074211', headers=headers).text, 'html.parser')
data = json.loads(d.select_one('script[data-react-helmet="true"][type="application/ld+json"]').contents[0])
price = data[2]['offers']['price']

輸出:

5.98

這是一個非常困難的網站。 您將無法使用該類名訪問價格。 如果您的站點具有 javascript DOM 元素,則網絡抓取會變得困難。 “查看源代碼”將獲得 Beautifulsoup 將獲得的響應。 仔細檢查后,您的頁面價格位於“腳本”標簽下的 json 值內:

import requests
from bs4 import BeautifulSoup
import json

HEADERS = {'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/91.0.4472.164 Safari/537.36"}

URL = "https://www.lowes.com/pd/2-in-x-4-in-x-8-ft-Whitewood-Stud-Common-1-5-in-x-3-5-in-x-96-in-Actual/1000074211"
r = requests.get(URL,headers=HEADERS)
soup = BeautifulSoup(r.content, "html.parser")
contents =  soup.find("script")
json_object = json.loads(contents.text)
print(json_object[2]["offers"]["price"])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM