简体   繁体   English

如何使用 selenium 从元素中获取文本

[英]How to get text from an element with selenium

I am trying to get text from an element and then searching for it in another place, the problem is that when I get the text using .text , I noticed that it misses if there is two spaces, and when it searches in the next page, it can't find it.我试图从一个元素中获取文本,然后在另一个地方搜索它,问题是当我使用.text获取文本时,我注意到如果有两个空格它会丢失,并且当它在下一页搜索时,它找不到它。 So is there a way to get text as it is with spaces?那么有没有办法让文本与空格一样?

Code:代码:

self.name = session.find_element('xpath', './/a[contains(@href, "name")]').text
self.dataBrowser.find_elements(By.XPATH, f'//tr[child::td[child::div[child::strong[text()="{self.name}"]]]]')

Not always the text property will actually hold the text.并非总是 text 属性实际上会保存文本。 So, try this:所以,试试这个:

element = browser.find_element(By.CSS, 'CSS_EXPRESSION')
text = element.get_attribute('text')
if text is None or text is '':
    text = element.get_attribute('value')

If text and value both returns nothing just try reading the innnerHTML attribute.如果 text 和 value 都没有返回任何内容,请尝试读取 innnerHTML 属性。

It's hard to say how “text” is defined in the context of this post, as long as it is a string literal.很难说在这篇文章的上下文中“文本”是如何定义的,只要它是一个字符串文字。 The fact that text has space before and after it (as well as between them) makes it very difficult to “get text from an element with selenium”, but think of it this way: you know that every element has a String in its dataDict attribute.文本前后(以及它们之间)有空格的事实使得“从带有 selenium 的元素中获取文本”变得非常困难,但是这样想:你知道每个元素的 dataDict 中都有一个字符串属性。 In other words, if you want to get text from an element, you need to do something like this: In other words, the following method will get the text from an element with selenium: And if you want to search for a string in another place (say, within an HTML site), you can do something like this: And then we can search for some text within HTML tags or CSS property names or whatever else we need.换句话说,如果你想从一个元素中获取文本,你需要做这样的事情:换句话说,下面的方法将从一个元素中获取文本 selenium:放置(例如,在 HTML 站点内),您可以执行以下操作:然后我们可以在 HTML 标记或 CSS 属性名称或我们需要的任何其他内容中搜索一些文本。 This way creates a bit of syntactic sugar for getting data from elements (which is also useful for getting text from HTML and JavaScript).这种方式为从元素获取数据创建了一些语法糖(这对于从 HTML 和 JavaScript 获取文本也很有用)。 But there are already better ways of doing things, such as using Python's pickle module directly or by using JSON serialization.但是已经有更好的处理方法了,比如直接使用 Python 的 pickle 模块或者使用 JSON 序列化。 I won't go into detail about how these methods work because they are used by people who have more knowledge than me on that topic but I'll just mention that those are generally easier to use and don't require knowing any particular programming language such as Python.我不会 go 详细介绍这些方法是如何工作的,因为在该主题上比我有更多知识的人使用它们,但我只想提一下,这些方法通常更易于使用并且不需要了解任何特定的编程语言如 Python。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM