获取硒中的特定元素 [英] Getting specific elements in selenium
问题描述
我试图在下图中显示为N06D-X N07X R01A-C01 S01G-X01的元素:
I am trying to get the elements displayed as N06D-X N07X R01A-C01 S01G-X01 in the following image:
现在,我通过这种方式获得了类似WebDriver的东西:
Now, I got something like the WebDriver in this way:
谁= driver.find_element_by_tag_name("span").find_elements_by_tag_name("p")
并获得如下输出:
[<selenium.webdriver.remote.webelement.WebElement (session="1c044455cf883fdedf6845bcd456bfab", element="0.23338884730774767-2")>]
我在Mac Catalina上工作,当我键入:who.text时,由于某种原因它返回一个空列表.我在使用Bs时遇到了类似的麻烦,但是我使用 .string
而不是 .text
解决了它们.在这里 .string
不适用于WebDriver元素.
I am working on Mac Catalina and when I type: who.text it returns an empty list for some reason. I got quite similar troubles with Bs but I solved them with .string
rather than .text
. Here .string
does not work on WebDriver elements.
问题是:我如何用硒获得N06D等物品?
The question is: how can I get the items N06D and so on with selenium?
推荐答案
看来您已经足够亲密了.
Seems you were pretty close enough.
[<selenium.webdriver.remote.webelement.WebElement (session="1c044455cf883fdedf6845bcd456bfab", element="0.23338884730774767-2")>]
代表您正在元素中寻找文本的位置的元素.
represents the element where as you were looking for the text within the element.
要提取文本,例如使用 python ,您必须诱使定位器策略:
To extract the texts e.g. N06D-X, N07X, etc from all of the <p>
tags using Selenium and python you have to induce WebDriverWait for visibility_of_all_elements_located()
and you can use either of the following Locator Strategies:
-
使用
CSS_SELECTOR
和get_attribute("innerHTML")
:
print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.data-list__property#who-atc-codes span.data-list__property-value p")))])
使用 XPATH
和 text 属性:
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//li[@class='data-list__property' and @id='who-atc-codes']//span[@class='data-list__property-value']//p")))])
注意:您必须添加以下导入:
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
链接到有用的文档:
-
get_attribute()
方法获取元素的给定属性或属性.
-
text
属性返回元素的文本.
- 使用Selenium的文本和innerHTML之间的区别
这篇关于获取硒中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!