Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Selenium如何选择正文中的最后一个链接?_Python_Selenium_Xpath - Fatal编程技术网

Python Selenium如何选择正文中的最后一个链接?

Python Selenium如何选择正文中的最后一个链接?,python,selenium,xpath,Python,Selenium,Xpath,我有一个html页面,如下所示 <body> <div> <a class="btn btn-info" href="a.php">A</a> <a class="btn btn-info" href="b.php">B</a> <a class="btn btn-

我有一个html页面,如下所示

<body>
    
    <div>
        <a class="btn btn-info" href="a.php">A</a>
        <a class="btn btn-info" href="b.php">B</a>
        <a class="btn btn-info" href="c.php">C</a>
        <a class="btn btn-info" href="d.php">D</a>
    </div>
        
    <a class="btn btn-info" href="f.php">F</a>

</body>
link = driver.find_element_by_xpath("//a[last()]")
它正在选择
D

我也试过下面的方法

email = driver.find_element_by_xpath("/body//a[last()]")

此时无法定位元素。如何轻松获取此处的最后一个链接?

使用
driver.findElements()
方法并将返回值放入数组中

最后一个链接将是数组的最后一个元素

我建议你(出于各种原因):

  • do
    yourArray=driver.findElements(By.tag(“a”))

  • 对于每个元素,使用
    element.getAttribute(“href”)!=null
    并更新myIndex变量(如果不是

  • “yourArray”的索引“myIndex”处的元素将是您正在搜索的元素


  • 获取最后一个元素。尝试以下
    xpath

    link = driver.find_element_by_xpath("(//a)[last()]")
    

    不可能使用last()方法吗?我建议您检查属性,WebElement不能以您想要的方式作为链接。我更喜欢写长的,也许效率较低,但可靠和安全的代码。