我有一個 HTML 檔案,該檔案包含幾個腳本,特別是在最后一個腳本中包含一個我想要獲取的值
我需要在這里找到哈希值
extend(cur, { "hash": "13334a0e457f0793ec", "loginHost": "login", "sureBoxText": false, "strongCode": 0, "joinParams": false, "validationType": 3, "resendDelay": 120, "calledPhoneLen": 4, "calledPhoneExcludeCountries": [1, 49, 200] });
為此我使用
import re
with open("test.html", "r", encoding='utf-8') as f:
html = f.read()
hash = re.search(r'{ "hash": "(.*?)",', html).group(1)
作業完美,但是當我嘗試直接從請求中執行相同操作時,錯誤。
with requests.get(url, headers=headers, cookies=cookies) as response:
if response.status_code == 200:
html = response.content
hash = re.search(r'{ "hash": "(.*?)",', html).group(1)
return hash
錯誤
TypeError: cannot use a string pattern on a bytes-like object
然后我執行了一個簡單的測驗,我將“response.text”保存在一個 html 檔案中,并嘗試以第一種方式讀取,在我輸入檔案后不久錯誤仍然存??在,在我的 vscode 中我點擊格式化檔案,它修復了整個 html 檔案,我執行了測驗并且它起作用了。我需要一種將“response.text”格式設定為 html 的方法,這樣我就可以獲得我的價值,或者如果有另一種方式我不知道我愿意學習。
OBS 哈希值在“response.text”中找到
uj5u.com熱心網友回復:
您需要將位元組解碼為字串:
re.search(r'{ "hash": "(.*?)",', html.decode('utf-8'))
uj5u.com熱心網友回復:
嘗試html使用str()以下方法轉換為字串:
hash = re.search(r'{ "hash": "(.*?)",', str(html)).group(1)
編輯:您的正則運算式不正確,將其更改為:
hash = re.search(r'"hash":"(.*?)",', str(html)).group(1)
uj5u.com熱心網友回復:
我相信您正在尋找response.text“回應的內容,以 unicode 格式。”。見https://2.python-requests.org/en/master/api/#requests.Response.text
with requests.get(url, headers=headers, cookies=cookies) as response:
if response.status_code == 200:
html = response.text
hash = re.search(r'{ "hash": "(.*?)",', html).group(1)
return hash
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/343232.html
