使用 xpath 在 selenium python 中选择文本节点 [英] selecting text node in selenium python with xpath

查看:31
本文介绍了使用 xpath 在 selenium python 中选择文本节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想选择带有 selenium 和 xpath 的 hr 节点之后的某些文本.但我不断收到 WebDriverException

这是我想从中提取文本的 html 代码:html 片段

我想得到的文字是:金融...商业决策简介

我使用了这个代码:

e = c.find_element_by_xpath("//div[@class='ajaxcourseindentfix']/hr/following-sibling::text()")

问题是我一直收到这个异常

selenium.common.exceptions.WebDriverException:消息:TypeError:需要一个元素或 WindowProxy,得到:[object Text] {}

我该怎么办?

解决方案

在 selenium 中,您不能使用返回属性或文本节点的 XPath,因此不允许使用 /text() 语法.如果您只想获取特定的子文本节点(节点)而不是完整的文本内容(由 text 属性返回),您可能会执行复杂的 JavaScript

我试图从这个问题中实施解决方案 它似乎有效,因此您可以应用以下代码来获取所需的文本节点:

driver.execute_script("""var el = document.createElement('html');el.innerHTML = '

'+ document.querySelector('div.ajaxcourseindentfix').innerHTML.split('<hr>')[1];返回 el.querySelector( 'div' ).textContent;""")

输出是

财务和管理会计理论与实践介绍,重点介绍会计信息在业务决策中的作用.

I want to select certain text that comes after an hr node with selenium and xpath. But I keep getting a WebDriverException

Here is the html code I want to extract the text from: html snippet

The text I want to get is: Introduction to financial ... business decisions

I used this code:

e = c.find_element_by_xpath("//div[@class='ajaxcourseindentfix']/hr/following-sibling::text()")

The problem is that I keep getting this exception

selenium.common.exceptions.WebDriverException: Message: TypeError: Expected an element or WindowProxy, got: [object Text] {}

What should I do?

解决方案

In selenium you cannot use XPath that returns attributes or text nodes, so /text() syntax is not allowed. If you want to get specific child text node (nodes) only instead of complete text content (returned by text property), you might execute complex JavaScript

I tried to implement solution from this question and it seem to work, so you can apply below code to get required text node:

driver.execute_script("""var el = document.createElement( 'html' );
                         el.innerHTML = '<div>' + document.querySelector('div.ajaxcourseindentfix').innerHTML.split('<hr>')[1];
                         return el.querySelector( 'div' ).textContent;""")

The output is

Introduction to financial and managerial accounting theory and practice with emphasis on the role of accounting information in business decisions.

这篇关于使用 xpath 在 selenium python 中选择文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆