【发布时间】:2021-12-30 08:44:49
【问题描述】:
我找到了一个网页的 json 响应,并使用下面的代码用 selenium 抓取了它:
from selenium import webdriver
url = "website.json"
driver.get(url)
text = driver.page_source
with open("data.json", "tw",encoding="utf-8") as html_file:
html_file.write(text)
但是当我打开文件时是这样的:
<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">{
"Status": "OK",
"TotalRows": 386,
"Items": [
...
]
}</pre></body></html>
所以json文件显示在两个html标签的中间。为了解决这个问题,我尝试了这段代码:
t1 = text.replace('<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">', "")
t2 = t1.replace('</pre></body></html>', "")
with open('data.json', 'w') as outfile:
json.dump(t2, outfile, indent=2)
但是当我运行它时,data.json 包含这样的字符串:
"{\n \"Status\": \"OK\",\n \"TotalRows\": 401,\n \"Items\": [\n ...\n ]\n}"
我该怎么办?
【问题讨论】: