我的代碼適用於一個站點而不是另一個站點。有人可以幫我嗎。
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())
解析 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 字典,因此示例代碼如下所示:requests
requests.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(需要登錄)。
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 我有一個專門的網絡抓取博客。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句