【问题标题】:How can I write a json webpage into a json file using selenium driver.page_source?如何使用 selenium driver.page_source 将 json 网页写入 json 文件?
【发布时间】: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}"

我该怎么办?

【问题讨论】:

    标签: python json selenium


    【解决方案1】:

    你应该尝试只找到你想要的元素并提取它的文本:

    driver.get(url)
    element = driver.findElement(By.TAG_NAME, 'pre')
    with open('data.json', 'w') as file:
        json.dump(element.text, file)
    

    【讨论】:

    • 我从inspect元素的Network tab找到了json文件。所以我需要我的 url 的整个 json 文件。
    • 您收到的字符串有什么问题?它是一个有效的 JSON,您可以将其保存到文件中。
    • 我也尝试过 requestsbs4,但 cloudflare 可以保护它。所以我必须只使用硒。这可能是由于 cloudflare 造成的!
    【解决方案2】:

    好像在清理HTML tags之后通过:

    t1 = text.replace('<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">', "")
    t2 = t1.replace('</pre></body></html>', "")
    

    我需要将t2 加载为 json 文件,如下所示:

    res = json.loads(t2)
    with open('data.json', 'w') as outfile:
        json.dump(res, outfile, indent=4)
    

    这对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 2017-06-29
      • 2018-12-25
      • 2015-12-09
      • 1970-01-01
      • 2020-03-08
      • 2016-04-13
      相关资源
      最近更新 更多