如何从Google Chrome Selenium Webdriver客户端获取JSON响应?

Rog*_*yer 8 python selenium-webdriver

目前我已经将Selenium连接到python来抓取一个网页.我发现页面实际上是从JSON API中提取数据,只要我登录到页面,我就可以获得JSON响应.

但是,我将这种响应转化为python的方法似乎有点混乱; 我选择包含在<pre>标签中的文本并使用python的json包来解析数据,如下所示:

import json
from selenium import webdriver

url = 'http://jsonplaceholder.typicode.com/posts/1'
driver = webdriver.Chrome()
driver.get(url)
json_text = driver.find_element_by_css_selector('pre').get_attribute('innerText')
json_response = json.loads(json_text)
Run Code Online (Sandbox Code Playgroud)

我需要在<pre>标签中选择的唯一原因是因为当JSON出现在Chrome中时,它的格式如下:

<html>
<head></head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}</pre>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我需要在selenium中完成此操作的唯一原因是因为我需要登录网站以获得响应.否则我得到401而没有数据.

ale*_*cxe 13

你可以找到该pre元素并获取它的文本,然后通过json.loads()以下方式加载它:

import json 

pre = driver.find_element_by_tag_name("pre").text
data = json.loads(pre)
print(data)
Run Code Online (Sandbox Code Playgroud)

此外,您可能避免使用selenium以获得所需的JSON数据和传输的cookie seleniumrequests保持"保持登录状态",请参阅:

  • 对于那些在 Firefox 中将 json-response 自动格式化为表格并更改源的人:在您的 url 前添加 **"view-source:"** 。然后您可以继续使用按标签查找“pre”。 (4认同)