我正在嘗試在 html 頁面的腳本中解析 JSON。
import requests
from bs4 import BeautifulSoup
import json
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36 OPR/64.0.3417.47",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "fr-FR,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
"Cache-Control": "max-age=0",
"Upgrade-Insecure-Requests": "1",
}
proxy = "http://stack:overflow@45.135.149.142:14758"
url = "https://www.seloger.com/list.htm?projects=2%2C5&types=2%2C1&natures=1%2C2%2C4&places=%5B%7Bci%3A60088%7D%5D&enterprise=0&qsVersion=1.0"
r = requests.get(url, proxies={"http": proxy, "https": proxy}, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
for script in soup.find_all('script'):
if "initialData" in script.text:
data = script.text.split('JSON.parse("', 1)[1].split('");window["tags"]', 1)[0]
json_data = json.loads(data)
並返回此錯誤:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
問題是 " 沒有轉換為引號 " ,這會觸發 json 解碼器錯誤。
此外,每當我打印腳本代碼時,都會打印 " 而不是 "。在將其傳遞給 json.loads 之前,我已經嘗試以多種格式進行編碼和解碼,但沒有任何效果。
只有在直接從請求響應中解析代碼時才會出現問題。 我無法復制這個問題。 此代碼按預期工作:
snippet = '''<script>
window["initialData"] = JSON.parse("{\u0022foo\u0022:\u0022bar\u0022,\u0022xxx\u0022:\u0022xyz\u0022}")
</script>
'''
soup = BeautifulSoup(snippet, 'html.parser')
for script in soup.find_all('script'):
data = script.text.split('JSON.parse("')[1].split('")')[0]
json_data = json.loads(data)
print(json_data)
# output : {'foo': 'bar', 'xxx': 'xyz'}
我怎樣才能解決這個問題?