获取硒中的特定元素

Getting specific elements in selenium

我试图让元素显示为下图中的 N06D-X N07X R01A-C01 S01G-X01:

现在,我通过这种方式得到了类似于 WebDriver 的东西:

who = 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 它 returns 由于某种原因是一个空列表。我遇到了与 Bs 非常相似的问题,但我用 .string 而不是 .text 解决了它们。这里 .string 不适用于 WebDriver 元素。

问题是:如何用selenium得到N06D等物品?

您不是在整个网站中搜索而是在之前找到的对象中搜索

li_object = driver.find_elements_by_id('who-atc-codes')
lst = li_object.find_element_by_tag_name("span").find_elements_by_tag_name("p")

for p in lst:
    print(p.text)
    print(p.get_attribute('innerHTML'))

或者你可以试试

span_object = li_object.find_element_by_tag_name("span")
print(span_object.get_attribute('innerHTML'))

使用以下 css selector 获取项目列表,然后迭代。

要获取文本您可以使用 .text.get_attribute("innterHTML").get_attribute("textContent")

代码:

items=driver.find_elements_by_css_selector("span.data-list__property-value>p")
for item in items:
    print(item.text)
    print(item.get_attribute("innterHTML"))
    print(item.get_attribute("textContent"))
    #To get only value from string use spilt and take the first element.
    print(item.text.strip().split(" ")[0])
    print(item.get_attribute("innterHTML").strip().split(" ")[0])
    print(item.get_attribute("textContent").strip().split(" ")[0])

看来你已经很接近了。

[<selenium.webdriver.remote.webelement.WebElement (session="1c044455cf883fdedf6845bcd456bfab", element="0.23338884730774767-2")>]

表示您在元素中查找文本的位置。

提取文本,例如N06D-XN07X 等来自所有使用 and you have to induce for visibility_of_all_elements_located() and you can use either of the following :

<p> 标签
  • 使用 CSS_SELECTORget_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")))])
    
  • 使用 XPATHtext 属性:

    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")))])
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

结尾

Link 到有用的文档:

  • get_attribute()方法Gets the given attribute or property of the element.
  • text属性returnsThe text of the element.
  • Difference between text and innerHTML using Selenium