我想用Chrome DevTools获取元素中的所有源代码。

虽然我尝试了以下代码,但这些值与上面的代码不匹配。
body = driver.execute_cdp_cmd("DOM.getOuterHTML", {"backendNodeId": 1})
print(body)是否有可能获得CDP的所有源代码?如何使用CDP获得所有源代码?
我知道另一种方法来刮源代码。但是我想知道如何在DevTools中获取元素中的源代码。(F12)
发布于 2022-04-30 23:37:37
编辑:参见末尾的CDP解决方案
假设"f12源代码“指的是”当前DOM,在它被JS或其他任何东西操作之后,而不是原始源代码“。
因此,请考虑以下html页面:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hi</title>
<script>
document.addEventListener("DOMContentLoaded", function(){
setTimeout(function(){
document.getElementById("test").innerHTML+=" World!"
}, 3000)
});
</script>
</head>
<body>
<h1 id="test">Hello</h1>
</body>
</html>
页面加载3秒后,h1将包含"Hello!“
这正是我们在运行以下代码时所看到的:
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
driver.get("http://localhost:8000/") # replace with your page
sleep(6) # probably replace with smarter logic
html = driver.execute_script("return document.documentElement.outerHTML")
print (html)产出:
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hi</title>
<script>
document.addEventListener("DOMContentLoaded", function(){
setTimeout(function(){
document.getElementById("test").innerHTML+=" World!"
}, 3000)
});
</script>
</head>
<body>
<h1 id="test">Hello World!</h1>
</body></html>编辑,使用 https://chromedevtools.github.io/devtools-protocol/ 代替:
您所描述的行为是奇怪的,但好的,让我们找一个不同的解决方案。
在python中的selenium 4中(到目前为止)似乎有对CDP的有限支持。到目前为止(2022年5月),python中没有driver.getDevTools(),只有java和JS (Node) (?)。
不管怎么说,我甚至不确定那会对我们有帮助。
到目前为止,原始CDP就足够了:
from selenium import webdriver
from time import sleep
# webdriver.remote.webdriver.import_cdp()
driver = webdriver.Chrome()
driver.get("http://localhost:8000/")
sleep(6)
doc = driver.execute_cdp_cmd(cmd="DOM.getDocument",cmd_args={})
doc_root_node_id = doc["root"]["nodeId"]
result = driver.execute_cdp_cmd(cmd="DOM.getOuterHTML",cmd_args={"nodeId":doc_root_node_id})
print (result['outerHTML'])指纹:
<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hi</title>
<script>
document.addEventListener("DOMContentLoaded", function(){
setTimeout(function(){
document.getElementById("test").innerHTML+=" World!"
}, 3000)
});
</script>
</head>
<body>
<h1 id="test">Hello World!</h1>
</body></html>https://stackoverflow.com/questions/72044097
复制相似问题