简体   繁体   English

使用 selenium xpath 定位元素

[英]Locate an element using selenium xpath

I am trying to locate an element that has the following line in the chrome inspect code, <href="app/arp/home/profile"> .我正在尝试在 chrome 检查代码<href="app/arp/home/profile">中找到具有以下行的元素。

My line is:我的线路是:

driver.find_element(By.xpath("//a[@href='/app/arp/home/profile']")).click()

But I get the following error:但我收到以下错误:

AttributeError: type object 'By' has no attribute 'xpath'

What is wrong?怎么了?

Till Selenium v3.141.0 to locate an element using you can use the following syntax: 在 Selenium v3.141.0使用定位元素之前,您可以使用以下语法:

driver.find_element_by_xpath("//a[@href='/app/arp/home/profile']")

However, in the upcoming releases find_element_by_* commands will be deprecated但是,在即将发布的版本中, find_element_by_*命令将被弃用

def find_element_by_xpath(self, xpath):
    """
    Finds an element by xpath.

    :Args:
     - xpath - The xpath locator of the element to find.

    :Returns:
     - WebElement - the element if it was found

    :Raises:
     - NoSuchElementException - if the element wasn't found

    :Usage:
        ::

            element = driver.find_element_by_xpath('//div/td[1]')
    """
    warnings.warn("find_element_by_* commands are deprecated. Please use find_element() instead")
    return self.find_element(by=By.XPATH, value=xpath)
        

From Selenium v4.x onwards the effective syntax will be:从 Selenium v4.x开始,有效语法为:

driver.find_element(By.XPATH, "//a[@href='/app/arp/home/profile']")

An example:一个例子:

  • Code Block:代码块:

     from selenium import webdriver from selenium.webdriver.common.by import By driver.get("https://www.google.com/") element = driver.find_element(By.NAME, "q") print(element) driver.quit()
  • Console Output:控制台 Output:

     <selenium.webdriver.remote.webelement.WebElement (session="04a9fac269c3a9cb724cc72769aed4e0", element="1b8ee8d0-b26a-4c67-be10-615286a4d427")>

Please try this one请试试这个

driver.find_element_by_xpath("//a[@href='/app/arp/home/profile']") driver.find_element_by_xpath("//a[@href='/app/arp/home/profile']")

AttributeError: type object 'By' has no attribute 'xpath'. AttributeError:类型 object 'By' 没有属性 'xpath'。

This means you didn't import the correct object By .这意味着您没有导入正确的 object By

Make sure to add the import on the top of the page:确保在页面顶部添加import

from selenium.webdriver.common.by import By 

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

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