目前在嘗試從網頁中提取以下文本時遇到了一些麻煩:
“https://www.johnlewis.com/mulberry-bayswater-small-zipped-leather-handbag-summer-khaki/p5807862”
我正在使用下面的代碼,我正在嘗試列印產品名稱、產品價格和庫存數量。
我可以輕松列印名稱和價格,但似乎無法列印庫存中的 #。
我試過同時使用StockInformation_stock__3OYkv&DefaultTemplate_product-stock-information__dFTUx但我要么一無所獲,要么再次出現價格。
我究竟做錯了什么?
提前致謝。
import requests
from bs4 import BeautifulSoup
url = 'https://www.johnlewis.com/mulberry-bayswater-small-zipped-leather-handbag-summer-khaki/p5807862'
response = requests.get(url, headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0'
})
soup = BeautifulSoup(response.content, 'html.parser')
numInStock = soup.find(class_="StockInformation_stock__3OYkv").get_text().strip()
productName = soup.find(id="confirmation-anchor-desktop").get_text().strip()
productPrice = soup.find(class_="ProductPrice_price__DcrIr").get_text().strip()
print (productName)
print (productPrice)
print (numInStock)
uj5u.com熱心網友回復:
您選擇的網頁有一些動態元素,即股票編號等快速變化的元素。在這種情況下,您拉取的頁面首先顯示更靜態的元素,例如產品名稱和價格,然后對庫存資料向不同的 API url 進行補充請求(因為它經常變化)。在瀏覽器請求補充資料后,它會將其注入到原始 HTML 頁面中,這就是為什么名稱和產品的框架在那里但沒有庫存的原因。簡而言之,當您發出抓取請求時,網頁“仍在加載”,并且還必須完成數百個對影像、檔案和資料的其他請求,才能獲取完整影像的其余資料您的瀏覽器和眼睛會經常看到。
幸運的是,我們只需要一個請求,即獲取股票資料。
為了解決這個問題,我們將對股票資訊的 URL 進行額外的請求。我不確定您對逆向工程了解多少,但我會稍微談一下。我做了一些逆向工程,發現它以帶有 json 引數的帖子形式發送到 https://www.johnlewis.com/fashion-ui/api/stock/v2 {"skus":["240280782"]} (skus 是產品串列)。網頁上有SKU,所以獲取庫存的完整代碼如下:
import requests
from bs4 import BeautifulSoup
url = 'https://www.johnlewis.com/longchamp-le-pliage-original-large-shoulder-bag/p5051141'
response = requests.get(url, headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0'
})
soup = BeautifulSoup(response.content, 'html.parser')
numInStock = soup.find(class_="StockInformation_stock__3OYkv").get_text().strip()
productName = soup.find(id="confirmation-anchor-desktop").get_text().strip()
# also find the sku by extracting the numbers out of the following mess found in the webpage: ......"1,150.00"},"productId":"5807862","sku":"240280782","url":"https://www.johnlewis.com/mulberry-ba.....
sku = response.text.split('"sku":"')[1].split('"')[0]
#supplemental request with the newfound sku
response1 = requests.post('https://www.johnlewis.com/fashion-ui/api/stock/v2', headers={
'authority': 'www.johnlewis.com',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36',
'content-type': 'application/json',
'accept': '*/*',
'origin': 'https://www.johnlewis.com',
'referer': 'https://www.johnlewis.com/mulberry-bayswater-small-zipped-leather-handbag-summer-khaki/p5807862',
}, json={"skus":[sku]})
# returns the json: {"stocks":[{"skuId":"240280782","stockQuantity":2,"availabilityStatus":"SKU_AVAILABLE","stockMessage":"Only 2 in stock online","lastUpdated":"2021-12-05T22:03:27.613Z"}]}
# index the json
try:
productPrice = response1.json()["stocks"][0]["stockQuantity"]
except:
print("There was an error getting the stock")
productPrice = "NaN"
print (productName)
print (productPrice)
print (numInStock)
我還確保通過其他產品進行測驗。由于我們通過步驟 1. 獲取頁面模板,然后步驟 2. 使用模板中的資料向服務器發出額外請求來動態模擬網頁所做的事情,因此它適用于任何產品 URL。
這是非常困難和痛苦的。如果您沒有完全理解,請不要打倒自己,因為您需要前端、后端、json 和決議的知識才能獲得它。
干杯!
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377771.html
