簡體   English   中英

使用 selenium xpath 定位元素

[英]Locate an element using selenium xpath

我正在嘗試在 chrome 檢查代碼<href="app/arp/home/profile">中找到具有以下行的元素。

我的線路是:

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

但我收到以下錯誤:

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

怎么了?

在 Selenium v3.141.0使用定位元素之前,您可以使用以下語法:

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

但是,在即將發布的版本中, 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)
        

從 Selenium v4.x開始,有效語法為:

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

一個例子:

  • 代碼塊:

     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()
  • 控制台 Output:

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

請試試這個

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

AttributeError:類型 object 'By' 沒有屬性 'xpath'。

這意味着您沒有導入正確的 object By

確保在頁面頂部添加import

from selenium.webdriver.common.by import By 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM