[英]Python Web browser click listener
Is there any packages or ways to detect what is being clicking in a web browser?是否有任何软件包或方法可以检测在 web 浏览器中单击的内容? I mean get tag/xpath from the web browser (of what is being clicked)?
我的意思是从 web 浏览器(被点击的内容)获取标签/xpath? To afterwards find it via selenium or similar?
之后通过 selenium 或类似的方式找到它?
Or even with to determine what it is with the coordinates of the mouse click.甚至用鼠标点击的坐标来判断它是什么。
Like the codegen in Playwright or similar, like a form of listening.就像 Playwright 中的 codegen 或类似的,就像一种聆听形式。
Hope this makes sense.希望这是有道理的。
We could add window listener with JavaScript using driver.execute_script
to listen to any clicks, and then call function xpath
as provided in SO answer to generate Xpath of an element.我们可以使用 driver.execute_script 添加 window 侦听器和
driver.execute_script
以侦听任何点击,然后调用function xpath
以生成元素的 Xpath。 As a gist, below is the window.addEventListener
script which handles any click
event by displaying an alert with the clicked element text (if present) and its Xpath:作为要点,下面是
window.addEventListener
脚本,它通过显示带有单击元素文本(如果存在)及其 Xpath 的警报来处理任何click
事件:
window.addEventListener('click', function(event) {alert(event.target.text+'=>'+xpath(event.target));})
And here is the relevant code to launch the browser, execute the script and sleep for 20 seconds to allow interaction on the browser:以下是启动浏览器、执行脚本并休眠 20 秒以允许在浏览器上进行交互的相关代码:
def launch_url(url):
driver = webdriver.Chrome('./chromedriver')
driver.get(url)
driver.execute_script('''
function xpath(el) {
if (typeof el == 'string') return document.evaluate(el, document, null, 0, null);
if (!el || el.nodeType != 1) return '';
if (el.id) return '//*[@id="' + el.id + '"';
var sames = [].filter.call(el.parentNode.children, function (x) { return x.tagName == el.tagName });
return xpath(el.parentNode) + '/' + el.tagName.toLowerCase() + (sames.length > 1 ? '['+([].indexOf.call(sames, el)+1)+']' : '')
}
window.addEventListener('click', function(event) {alert(event.target.id+'=>'+xpath(event.target));})
''')
time.sleep(20)
As a test, launched the SO main questions page with launch_url("https://stackoverflow.com/questions")
and clicked on the "Ask Question" button:作为测试,使用
launch_url("https://stackoverflow.com/questions")
启动 SO 主要问题页面并单击“提问”按钮:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.