簡體   English   中英

request.get()無法在python 2.7中檢索正確的url

[英]requests.get() not retrieving correct url in python 2.7

我正在嘗試訪問url,然后根據標簽解析其內容。 我的代碼:

page = requests.get('https://support.apple.com/downloads/')
self.tree = html.fromstring(page.content)
names = self.tree.xpath("//span[@class='truncate_name']//text()")

問題:變量頁面包含URL'https 'https://support.apple.com/'數據,我是python 2.7的新手。 文件中的整個編碼問題。 我使用unicode-escape作為默認編碼。 上在資源編碼https://support.apple.com/downloads/utf-8而資源的編碼在https://support.apple.com/是可變的。 這與問題有關嗎? 請為此提出解決方案。

它與編碼無關,您要查找的內容是動態創建的,因此不在返回源中。 一系列的ajax調用填充了數據。 要從輪播中獲取產品名稱等,您將在瀏覽器中看到span.truncate_name

params = {"page": "products",
          "locale": "en_US",
          "doctype": "DOWNLOADS",
          }
js = requests.get("https://km.support.apple.com/kb/index", params=params).content

通常我們可以在響應對象上調用.json() ,但是在這種情況下,我們需要使用"unicode_escape"然后調用loads

from json import loads, dumps
js2 = loads(js.decode("unicode_escape"))
print(js2)

這給了您巨大的數據量,例如:

{u'products': [{u'name': u'Servers and Enterprise', u'urlpath': u'serversandenterprise', u'order': u'', u'products': .............

您可以在Chrome工具中查看請求:

在此處輸入圖片說明

我們callback:ACDow‌​nloadSearch.customCa‌​llBackcallback:ACDow‌​nloadSearch.customCa‌​llBack因為我們想獲取有效的json。

暫無
暫無

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

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