我的代碼適用于一個站點而不是另一個站點。有人可以幫我嗎。
import requests
from bs4 import BeautifulSoup
URL = "https://www.homedepot.com/s/311256393"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find(id="root")
print(results.prettify())
下面的代碼顯示輸出的地方,網站上有什么區別嗎?
import requests
from bs4 import BeautifulSoup
URL = "https://realpython.github.io/fake-jobs/"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find(id="ResultsContainer")
print(results.prettify())
uj5u.com熱心網友回復:
決議 The Home Depot 時,您需要使用代理(如果您的 IP 在美國境外,否則會拋出拒絕訪問錯誤)并決議來自其 GraphQL API ( Dev Tools -> Network -> Fetch\XHR -> find appropriate name -> Headers (opened tab on the right after clicking on the name) -> URL)的資料并向適當的 URL 地址發出請求。
然后通過library:使用JSON 回應內容,它將 JSON 字串解碼為 Python 字典,因此示例代碼如下所示:requestsrequests.get("URL").json()
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
# additional headers if response is not 200 (look inside "Headers tab in Devtools")
}
response = requests.get('URL', headers=headers).json()
some_variable = response['some_dict_key_from_response']
或者,如果您不想處理繞過塊,您可以使用SerpApi的 Home Depot Search Engine Results API獲得所需的輸出。這是一個帶有免費計劃的付費 API。
不同之處在于你不必像上面提到的那樣處理塊,弄清楚如何縮放請求的數量(如果需要),并且不需要隨著時間的推移維護它(如果 HTML 中的某些內容會發生變化) . 使用您正在尋找的產品查看Playground(需要登錄)。
在線IDE中集成和示例的示例代碼:
from serpapi import GoogleSearch
import os
params = {
"api_key": os.getenv("API_KEY"),
"engine": "home_depot_product", # ↓↓↓
"product_id": "311256393" # https://www.homedepot.com/s/311256393 ←
# ↑↑↑
}
search = GoogleSearch(params)
results = search.get_dict()
title = results["product_results"]["title"]
link = results["product_results"]["link"]
price = results["product_results"]["price"]
rating = results["product_results"]["rating"]
print(title, link, price, rating, sep="\n")
# actual JSON response is much bigger
'''
20 in. x 20 in. Palace Tile Outdoor Throw Pillow with Fringe
https://www.homedepot.com/p/Hampton-Bay-20-in-x-20-in-Palace-Tile-Outdoor-Throw-Pillow-with-Fringe-7747-04413111/311256393
19.98
5.0
'''
快速瀏覽一下product_results:
for key in results["product_results"]:
print(key, sep="\n")
'''
product_id
title
description
link
upc
model_number
favorite
rating
reviews
price
highlights
brand
images
bullets
specifications
fulfillment
'''
免責宣告,我為 SerpApi 作業。
PS 我有一個專門的網路抓取博客。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/361677.html
上一篇:Scrapy不遵循新的請求
下一篇:使用Rvest從網路中提取影像
