這個賞金已經結束。此問題的答案有資格獲得 50聲望賞金。賞金寬限期在13 小時后結束。 Alain想引起更多人對這個問題的關注。
編輯 3:在開頭添加 TL:DR:
- 轉到此網址:https ://www.homedepot.com.mx/banos/accesorios-para-bano/juegos-de-accesorios/accesorios-bao-adelyn-4-piezas-cromo-130389
- 單擊添加到購物車按鈕下方幾行的“Revisa disponibilidad en tiendas aquí”鏈接。
- 將出現一個彈出視窗,其中包含不同商店的產品庫存資訊。在開發人員工具的網路選項卡中,我可以看到在向https://www.homedepot.com.mx/GetStorePopUpInventoryStatusByIDView發出請求后收到此庫存資訊。有關如何呼叫的更多詳細資訊,請參見下文
- 我需要構建一個呼叫此請求的 Python 腳本,而不會出現我現在遇到的遺傳錯誤,我認為這是由于與會話、cookie 或授權相關的某些事情。
原始問題:
我正在執行一項任務,使用 python 從網站獲取特定產品的庫存資訊
產品網址為: https ://www.homedepot.com.mx/banos/accesorios-para-bano/juegos-de-accesorios/accesorios-bao-adelyn-4-piezas-cromo-130389
我對呼叫 post/get 請求很陌生,但是通過研究瀏覽器網路選項卡中的資訊,我發現我可以通過單擊“Revisa disponibilidad en tiendas aquí”鏈接來獲取所需的資訊他添加到購物車按鈕下方的行。在網路選項卡中,我可以看到此鏈接呼叫此請求:
https://www.homedepot.com.mx/GetStorePopUpInventoryStatusByIDView
如果我將 url 與它使用的引數連接起來,我會得到:
https://www.homedepot.com.mx/GetStorePopUpInventoryStatusByIDView?storeId=10351&catalogId=10101&langId=-5&physicalStoreListIds=12511%2C12524%2C12539%2C12542%2C12552%2C12583%2C12591%2C12592%2C12598%2C12605%2C12613%2C12614%2C12616%2C14003&productId=378219&fulfilment_type=Store&productavailable=true&type=ItemBean&catalogEntryIdToUse=378219&sibstore=12511%2C12524%2C12539%2C12542%2C12552%2C12583%2C12591%2C12592%2C12598%2C12605%2C12613%2C12614%2C12616%2C14003&requesttype=ajax&authToken=-1002%2Chqj050NRqj8jCOeOf8xNj4dGjQaR1rxBdxDNL2QdATA%3D
如果我直接在瀏覽器中運行它,我會得到我需要的資訊:
/* {"InventoryAvailability": [ {"physicalStoreName": "8860", "availableQuantity": "0"}, {"physicalStoreName": "8762", "availableQuantity": "7"}, {"physicalStoreName": "8661", "availableQuantity": "17"}, {"physicalStoreName": "8798", "availableQuantity": "2"}, {"physicalStoreName": "8744", "availableQuantity": "0"}, {"physicalStoreName": "8763", "availableQuantity": "0"}, {"physicalStoreName": "1165", "availableQuantity": "13"}, {"physicalStoreName": "8691", "availableQuantity": "18"}, {"physicalStoreName": "8692", "availableQuantity": "15"}, {"physicalStoreName": "8648", "availableQuantity": "13"}, {"physicalStoreName": "8747", "availableQuantity": "0"}, {"physicalStoreName": "8748", "availableQuantity": "0"}, {"physicalStoreName": "8702", "availableQuantity": "14"}, {"physicalStoreName": "8746", "availableQuantity": "0"}] }*/
現在,我嘗試構建一個 python 腳本來復制它,但是當我運行它時,我得到了這個錯誤回應:
{"errorCode": "2540",
"errorMessage": "CMN3101E El sistema no est??? disponible debido a \"ErrorCode=2540\n\".",
"errorMessageKey": "_ERR_GENERIC",
"errorMessageParam": [{"ErrorCode": "2540"}],
"correctiveActionMessage": "",
"correlationIdentifier": "3bff941d:1814799a223:-4d74",
"exceptionData": {"ErrorCode": "2540"},
"exceptionType": "1",
"originatingCommand": "",
"systemMessage": "El error siguiente se ha producido durante el proceso: \"ErrorCode=2540\n\"."}*/
正如我所說,這是我第一次嘗試在 python 腳本中使用請求,所以也許我做錯了什么。我認為它可能與 authtoken 引數有關,但我不確定如何處理它。有沒有辦法將它從瀏覽器傳遞到腳本?這是我的代碼。有什么建議么?
import requests
url = 'https://www.homedepot.com.mx/GetStorePopUpInventoryStatusByIDView'
payload = {
"storeId":"10351",
"catalogId":"10101",
"langId":"-5",
"physicalStoreListIds":"12511%2C12524%2C12539%2C12542%2C12552%2C12583%2C12591%2C12592%2C12598%2C12605%2C12613%2C12614%2C12616%2C14003",
"productId":"378219",
"fulfilment_type":"Store",
"productavailable":"true",
"type":"ItemBean",
"sibstore":"12511%2C12524%2C12539%2C12542%2C12552%2C12583%2C12591%2C12592%2C12598%2C12605%2C12613%2C12614%2C12616%2C14003",
"requesttype":"ajax",
"authToken":"-1002%2Chqj050NRqj8jCOeOf8xNj4dGjQaR1rxBdxDNL2QdATA%3D"
}
x = requests.post(url, data=payload)
print(x.text)
編輯:看來我的問題還不夠清楚。對于那個很抱歉。所以這里有一個更詳細的總結:
我需要構建一個 Python 腳本以某種方式獲取此 URL 中的產品庫存:https ://www.homedepot.com.mx/banos/accesorios-para-bano/juegos-de-accesorios/accesorios-bao-adelyn -4-piezas-cromo-130389
在產品頁面中,如果我點擊添加到購物車按鈕下方的“Revisa disponibilidad en tiendas aquí”鏈接,則會出現一個彈出視窗,其中包含所有物體店的產品庫存。
從 chrome 的開發人員工具中的網路選項卡,我可以看到這個彈出視窗充滿了這個 POST 請求的輸出:https ://www.homedepot.com.mx/GetStorePopUpInventoryStatusByIDView
如果我通過連接有效負載中的所有引數從瀏覽器運行相同的請求,我會收到包含我需要的庫存資訊的回應。只要我不關閉它,這只適用于我的瀏覽器。如果我在另一個瀏覽器上嘗試,在隱身模式或 python 腳本中,我會得到原始問題中描述的錯誤。這是一個示例有效載荷:
storeId=10351&catalogId=10101&langId=-5&physicalStoreListIds=12505%2C12521%2C12554%2C12555%2C12565%2C12567%2C12578%2C12585%2C12609%2C14503&productId=208282&fulfilment_type=Store&productavailable=true&type=ItemBean&catalogEntryIdToUse=208282&sibstore=12505%2C12521%2C12554%2C12555%2C12565%2C12567%2C12578%2C12585%2C12609%2C14503&displayPopupSiblingstores=&requesttype=ajax&authToken=-1002%2Chqj050NRqj8jCOeOf8xNj4dGjQaR1rxBdxDNL2QdATA%3D我做了一個測驗腳本(代碼在上面),試圖運行請求,傳遞有效載荷的引數,但也得到了同樣的錯誤。
正如我所說,我對從腳本運行請求(GET 或 POST)很陌生。但我的理論是這個錯誤是由于有效載荷中的 authtoken 引數造成的。我需要以某種方式獲得一個有效的 authtoken(來自瀏覽器或腳本)并使用它來執行我的請求。至少這是我的理論,但我不確定。那是對的嗎?如果是,我該怎么做?如果沒有,我還能嘗試什么?
編輯2:
我用來檢查 mechanize 的測驗代碼,在檢查 resp2.read() 時仍然出現相同的錯誤:
import time
import mechanize
from bs4 import BeautifulSoup
br = mechanize.Browser()
resp = br.open("https://www.homedepot.com.mx/banos/accesorios-para-bano/juegos-de-accesorios/accesorios-bao-adelyn-4-piezas-cromo-130389")
html_string = (resp.read()).decode("utf-8")
# f = open("resp.html", "a")
# f.write(html_string)
# f.close()
time.sleep(5)
soup = BeautifulSoup(html_string, "html.parser")
tmp = soup.find("div", {"id": "physicalSelectedStoreList"})
refresh_url = tmp["refreshurl"]
print("refresh_url: {}".format(refresh_url))
print("")
authtoken_full = refresh_url.split("authToken=")[1]
print("authtoken_full: {}".format(authtoken_full))
authtoken = authtoken_full.split("&storeId")[0]
print("authtoken: {}".format(authtoken))
req_url = "https://www.homedepot.com.mx/GetStorePopUpInventoryStatusByIDView?storeId=10351&catalogId=10101&langId=-5&physicalStoreListIds=12505%2C12521%2C12554%2C12555%2C12565%2C12567%2C12578%2C12585%2C12609%2C14503&productId=208282&fulfilment_type=Store&productavailable=true&type=ItemBean&catalogEntryIdToUse=208282&sibstore=12505%2C12521%2C12554%2C12555%2C12565%2C12567%2C12578%2C12585%2C12609%2C14503&displayPopupSiblingstores=&requesttype=ajax&authToken="
req_url = req_url authtoken
print("")
print("Full request: {}".format(req_url))
time.sleep(5)
resp2 = br.open(req_url)
time.sleep(5)
print("")
print(">>>>>>>>>>>>>>> info")
print(resp2.info())
print(">>>>>>>>>>>>>>> read")
print(resp2.read())
uj5u.com熱心網友回復:
如果 URL 在您的一個瀏覽器中按預期作業,但在 Python 中使用時有所不同,則解決方案可能是通過提供User-Agent標頭 ( https://en.wikipedia.org/wiki/User_agent )使用您的原始字串模擬瀏覽器請求:
import requests
url = 'https://www.homedepot.com.mx/GetStorePopUpInventoryStatusByIDView?storeId=10351&catalogId=10101&langId=-5&physicalStoreListIds=12511%2C12524%2C12539%2C12542%2C12552%2C12583%2C12591%2C12592%2C12598%2C12605%2C12613%2C12614%2C12616%2C14003&productId=378219&fulfilment_type=Store&productavailable=true&type=ItemBean&catalogEntryIdToUse=378219&sibstore=12511%2C12524%2C12539%2C12542%2C12552%2C12583%2C12591%2C12592%2C12598%2C12605%2C12613%2C12614%2C12616%2C14003&requesttype=ajax&authToken=-1002%2Chqj050NRqj8jCOeOf8xNj4dGjQaR1rxBdxDNL2QdATA%3D'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
response = requests.get(url, headers=headers)
print(response.content)
如何使用 Python 請求來偽造瀏覽器訪問并生成用戶代理?
uj5u.com熱心網友回復:
我能給你一個 hacky 方法,在你的本地機器上安裝 postman,然后點擊你想要從中獲取資料的端點。確保您得到正確的回應,然后一旦您確認,在 Postman 中您可以選擇將呼叫轉換為 python/node/curl。等。確保您的通話正常,然后可以切換到任何語言的最簡單方法!
uj5u.com熱心網友回復:
Getting generic error when trying to run post request因為創建
/排序/搜索 url 獲取正確方法的不正確方式。因此POST創建將生成發布請求的正確 url。
例子:
從這里轉到域 url
繼續 Departmentos > Banos > Accesorios para banos 并點擊
Accesorios para banos然后你會得到下面的分頁鏈接
現在轉到 devtools > network tab > XHR 并單擊 paginaton url 中的第二頁并重繪
然后,您將通過單擊此處名稱列中的鏈接找到 POST 請求 url
腳本:
import requests
from bs4 import BeautifulSoup
#url = "https://www.homedepot.com.mx/banos/accesorios-para-bano#facet:&productBeginIndex:40&facetLimit:&orderBy:&pageView:grid&minPrice:&maxPrice:&pageSize:&"
api_url = "https://www.homedepot.com.mx/ProductListingView?top_category3=&top_category2=&top_category5=&top_category4=&advancedSearch=&manufacturer=&metaData=&enableSKUListView=false&catalogId=10101&searchTerm=&resultsPerPage=20&filterFacet=&resultCatEntryType=&gridPosition=&top_category=10003&categoryFacetHierarchyPath=&ajaxStoreImageDir=/wcsstore/HDM-SAS/&searchType=&filterTerm=&searchTermScope=&storeId=10351&ddkey=ProductListingView_4_-2011_3074457345618262063&sType=SimpleSearch&emsName=Widget_CatalogEntryList_701_3074457345618262063&disableProductCompare=false&langId=-5&facet=&categoryId=10520&parent_category_rn=10003&mainCount="
payload = 'contentBeginIndex=0&productBeginIndex=20&beginIndex=20&orderBy=&facetId=&pageView=grid&resultType=products&orderByContent=&searchTerm=&facet=&facetLimit=&minPrice=&maxPrice=&pageSize=&storeId=10351&catalogId=10101&langId=-5&homePageURL=https://www.homedepot.com.mx&commandContextCurrency=MXN&enableSKUListView=false&widgetPrefix=4_3074457345618262063&pgl_widgetId=3074457345618262063&requesttype=ajax'
headers= {
'content-type':'application/x-www-form-urlencoded',
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
'x-requested-with': 'XMLHttpRequest'
}
res = requests.post(api_url, headers=headers,data=payload)
soup = BeautifulSoup(res.content, "lxml")
for card in soup.select("div.product"):
product_name = card.select_one('div.product_info a:nth-child(2)').text
print(product_name)
product_url= 'https://www.homedepot.com.mx' card.select_one('div.product_info a:nth-child(2)').get('href')
print(product_url)
輸出:
CORTINA PARA BA?O FRANJA TRANSPARENTE
https://www.homedepot.com.mx/banos/accesorios-para-bano/cortinas-y-cortineros/cortina-para-bano-franja-transparente-877867
PORTARROLLO PARA BA?O ISO DE METAL MOEN
https://www.homedepot.com.mx/banos/accesorios-para-bano/porta-papel/portarrollo-iso-cromo-876922
TOALLERO DE ARGOLLA METAL PLATA
https://www.homedepot.com.mx/banos/accesorios-para-bano/toalleros/toallero-de-argolla-iso-cromo-876827
TOALLERO DE BARRA METAL PLATA
https://www.homedepot.com.mx/banos/accesorios-para-bano/toalleros/toallero-de-barra-de-24-iso-cromo-876819
JABONERA ISO DE METAL MOEN
https://www.homedepot.com.mx/banos/accesorios-para-bano/jaboneras/jabonera-iso-cromo-876764
GANCHO INDIVIDUAL PARA BATAS MOEN CROMO
https://www.homedepot.com.mx/banos/accesorios-para-bano/ganchos-para-toalla/gancho-iso-cromo-876713
CEPILLERA DE METAL CROMADO MOEN
https://www.homedepot.com.mx/banos/accesorios-para-bano/accesorios-de-pared/cepillera-iso-cromo-876693
JUEGO DE ACCESORIOS PARA BA?O PRESTON MOEN 6 PIEZAS
https://www.homedepot.com.mx/banos/accesorios-para-bano/juegos-de-accesorios/juego-de-accesorios-de-bano-preston-6-piezas-pewter-mate-858325
JUEGO DE ACCESORIOS PARA BA?O PRESTON MOEN 6 PIEZAS
https://www.homedepot.com.mx/banos/accesorios-para-bano/juegos-de-accesorios/juego-de-accesorios-de-bano-preston-6-piezas-cromo-858317
JUEGO DE ACCESORIOS PARA BA?O MOEN 6 PIEZAS
https://www.homedepot.com.mx/banos/accesorios-para-bano/juegos-de-accesorios/juego-de-accesorios-de-bano-aspen-6-piezas-cromo-858262
TOALLERO CORTO LATóN PLATA
https://www.homedepot.com.mx/banos/accesorios-para-bano/toalleros/toallero-explora-cromo-helvex-803147
PORTARROLLOS DE PAPEL HIGIéNICO BUILDERS 23.7 X 4.9 CM PLATA GLACIER BAY
https://www.homedepot.com.mx/banos/accesorios-para-bano/porta-papel/portarrollos-builders-niquel-800416
PORTARROLLOS BUILDERS 9 1/2 PULGADAS PLATA GLACIER BAY
https://www.homedepot.com.mx/banos/accesorios-para-bano/porta-papel/portarrollos-builders-cromo-800412
BUILDERS TOALLERO DE 65.7 CM PLATA GLACIER BAY
https://www.homedepot.com.mx/banos/accesorios-para-bano/toalleros/toallero-builders-niquel-61-cm-800404
TOALLERO BUILDERS DE 65.7 CM PLATA GLACIER BAY
https://www.homedepot.com.mx/banos/accesorios-para-bano/toalleros/toallero-builders-cromo-61-cm-800400
ARO PARA TOALLA GRIS GLACIER BAY
https://www.homedepot.com.mx/banos/accesorios-para-bano/toalleros/toallero-aro-builders-niquel-800388
TOALLERO ARO BUILDERS CROMO
https://www.homedepot.com.mx/banos/accesorios-para-bano/toalleros/toallero-aro-builders-cromo-800384
GANCHO PARA BATA ROBE HOOK DE 3.5 PULGADAS PLATA GLACIER BAY
https://www.homedepot.com.mx/banos/accesorios-para-bano/ganchos-para-toalla/gancho-builders-niquel-800348
GANCHO PARA BATA BUILDERS PLATA GLACIER BAY
https://www.homedepot.com.mx/banos/accesorios-para-bano/ganchos-para-toalla/gancho-builders-cromo-800344
CORTINERO AJUSTABLE 183 CM BLANCO OXAL
https://www.homedepot.com.mx/banos/accesorios-para-bano/cortinas-y-cortineros/cortinero-ajustable-105-183-cm-blanco-730540
更新:
import requests
api_url = 'https://www.homedepot.com.mx/GetStorePopUpInventoryStatusByIDView'
payload = 'emarsysItem_0=128147&title_128147=REPISA MELAMINA TEXTURIZADA 30X60X1.6 CM GINGER&description_128147=Repisa ginger c/text 30x60x1.6cm&brand_128147=MADERAS Y DISEÑOS&link_128147=https://www.homedepot.com.mx/decoracion/repisas-y-accesorios/repisas-35509-5/repisa-ginger-context-maderas-y-disenos-del-norte-128147&available_128147=true&storeId=10351&catalogId=10101&physicalStoreValue=1168&emarsysRecomendadosCount=10¤tProtocalType=https:&containerID=carrusel2&emarsysItem_1=139926&title_139926=REPISA DE TABLERO LAMINADO DE 60.2 X 14.3 X 14.4 CM NOGAL TEXTURIZADO&description_139926=Repisa de 60.2 x 14.3 x 14.4 cm Playcon producto estético que proporciona un espacio donde colocar diversos objetos con capacidad de soporte de hasta 25 kg. Fabricada en tablero laminado con vinil color café nogal y acabado texturizado.&brand_139926=PLAYCON&link_139926=https://www.homedepot.com.mx/decoracion/repisas-y-accesorios/repisas-35509-5/repisa-opciones-playcon-602x143x144cm-nogal-139926&available_139926=true&emarsysItem_2=827631&title_827631=REPISA DE MELAMINA DE 30 X 60 CM&description_827631=Repisa de Melamina con textura en tamaño de 30 x 60 centímetros fabricada en color blanco con acabado mate.&brand_827631=MADERAS Y DISEÑOS&link_827631=https://www.homedepot.com.mx/decoracion/repisas-y-accesorios/repisas-35509-5/repisa-blanca-con-textura-30-x-60-x-16-cm-827631&available_827631=true&emarsysItem_3=139927&title_139927=REPISA DE TABLERO LAMINADO DE 60.2 X 14.3 X 14.4 CM GRIS TEXTURIZADO&description_139927=Repisa de 60.2 x 14.3 x 14.4 cm Playcon producto estético que proporciona un espacio donde colocar diversos objetos con capacidad de soporte de hasta 25 kg. Fabricada en tablero laminado con vinil color gris y acabado texturizado.&brand_139927=PLAYCON&link_139927=https://www.homedepot.com.mx/decoracion/repisas-y-accesorios/repisas-35509-5/repisa-opciones-playcon-60-cm-gris-touch-139927&available_139927=true&emarsysItem_4=705951&title_705951=REPISA NEGRA DE MELAMINA DE 12 X 24 PULGADAS&description_705951=Repisa Negra de Melamina de 12 x 24 pulgadas permite ajustarse a varios tipos de ménsula para su fácil instalación. Se puede limpiar con un paño húmedo.&brand_705951=MADERAS Y DISEÑOS&link_705951=https://www.homedepot.com.mx/decoracion/repisas-y-accesorios/repisas-35509-5/repisa-negra-con-textura-30-x-60-x-16-cm-705951&available_705951=true&emarsysItem_5=603560&title_603560=CLIPS PLÁSTICO ATTIKA BLANCO 16 MM&description_603560=Clips de plástico Attika color blanco 16 mm están fabricados en plástico de alta resistencia y cuentan con un diseño moderno que soporta hasta 20 kg son útiles para repisas de madera de 16 mm de ancho y hasta 20 cm de profundidad.&brand_603560=ATTIKA&link_603560=https://www.homedepot.com.mx/decoracion/repisas-y-accesorios/mensulas-y-accesorios-35511-5/clip-para-madera-16-mm-par-blanco-603560&available_603560=true&emarsysItem_6=127586&title_127586=CLIP PLÁSTICO NEGRO (PAR)&description_127586=Clips de plástico de alta resistencia para repisas de madera de 16 mm de ancho y hasta 15 cm de profundidad. Soporta hasta 15 kg de peso.&brand_127586=ATTIKA&link_127586=https://www.homedepot.com.mx/decoracion/repisas-y-accesorios/mensulas-y-accesorios-35511-5/clip-madera-16mm-par-negro-127586&available_127586=true&emarsysItem_7=603562&title_603562=CLIP PLÁSTICO DE 16 MILÍMETROS&description_603562=Diseño simple y funcional.Fácil de instalarcorrectamente instalado carga hasta 20 kgs repartidos (par).Material plástico extra resistente.Para repisas de madera de 16 mm de ancho y hasta 20 cm de profundidad&brand_603562=ATTIKA&link_603562=https://www.homedepot.com.mx/decoracion/repisas-y-accesorios/mensulas-y-accesorios-35511-5/clip-madera-16-mm-par-plata-603562&available_603562=true&emarsysItem_8=122442&title_122442=REPISA DOBLE CAJÓN ESPRESSO 120 X 29 X 13 CM&description_122442=Repisa decorativa con sistema de montaje oculto color chocolate dos cajones con correderas de extensión total acabado de gran resistencia. Herrajes metálicos. Soporta hasta 30kg.&brand_122442=CAPELLI&link_122442=https://www.homedepot.com.mx/decoracion/repisas-y-accesorios/repisas-35509-5/repisa-doble-cajon-expresso-120x29x13-cm-122442&available_122442=true&emarsysItem_9=134556&title_134556=REPISA DECORATIVA MADERAS Y DISEÑOS DEL NORTE DE 29 X 55 X 1.7 CM CAFÉ&description_134556=Repisa decorativa Maderas y Diseños del Norte de 29 x 55 x 1.7 cm color café su cuerpo está fabricado en melamina y puede ajustarse a varios tipos de ménsula. Es de fácil instalación y limpieza con un paño húmedo.&brand_134556=null&link_134556=https://www.homedepot.com.mx/decoracion/repisas-y-accesorios/repisas-35509-5/repisa-promo-expo-2x1-29-x-55-cm-134556&available_134556=true&displayType=Regular&requesttype=ajax&authToken=-1002%2Chqj050NRqj8jCOeOf8xNj4dGjQaR1rxBdxDNL2QdATA%3D'
headers= {
'content-type':'application/x-www-form-urlencoded',
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
'x-requested-with': 'XMLHttpRequest'
}
res = requests.post(api_url, headers=headers,data=payload)
print(res)
輸出:
<Response [200]>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/493690.html
