简体   繁体   English

xpath 用于单击按钮 - python/selenium

[英]xpath for click to a button - python/selenium

I'm trying to access a homepage, make login, click the login button and click a button (in the second page) using python/selenium.我正在尝试使用 python/selenium 访问主页,进行登录,单击登录按钮并单击按钮(在第二页中)。

The login button I wrote using Xpath and it's working well.我使用 Xpath 编写的登录按钮运行良好。 The browser opens, writes user and login and click the login button.浏览器打开,写入用户和登录名,然后单击登录按钮。

Unfortunately, in the next page I'm not able to click on the button that I need to.不幸的是,在下一页中我无法点击我需要的按钮。 It didn't work using Xpath and I can't understand why.使用 Xpath 无效,我不明白为什么。 The html is completely different from the first button, the button name is 'Reservar' and it is inside a class named <app-menu__menu>, written as: html与第一个按钮完全不同,按钮名称为'Reservar',它在一个名为<app-menu__menu>的class中,写为:

<a href="/Services" id="advanced" class="element  ">
                    
                    <span>Reservar</span>
                </a>

The xpath I got and tried:我得到并尝试过的 xpath:

xpath = "//*[@id="advanced"]"

Then I tried a second verion (it was gotten as the second line code xpath):然后我尝试了第二个版本(它是作为第二行代码 xpath 获得的):

xpath = "//*[@id="advanced"]/span"

When I first tried to used them, I got an error.当我第一次尝试使用它们时,出现错误。 Then I change the "" to ' ' and the error was gone.然后我将“”更改为“”,错误消失了。 But the program can't locate the button.但是程序找不到按钮。

I'm using google-chrome, ubuntu, python3 and selenium package:我正在使用谷歌浏览器、ubuntu、python3 和 selenium package:

driver.find_element_by_xpath(xpath).click()

Thanks for any help.谢谢你的帮助。

You probably missing a delay / wait.您可能错过了延迟/等待。
After clicking the submit / login button on the login page it takes some time to make the internal page loaded.单击登录页面上的提交/登录按钮后,需要一些时间来加载内部页面。
The recommended way to do that is to use Expected Conditions explicit waits, something like this:推荐的方法是使用预期条件显式等待,如下所示:

wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='advanced']"))).click()

To use the wait object here you will need to import the following inports:要在这里使用wait object,您需要导入以下输入端口:

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

And to initialize the wait object with并初始化wait object

wait = WebDriverWait(driver, 20)

You will have to validate your locator is unique.您将必须验证您的定位器是唯一的。 As well as to validate the element you are trying to access is not inside iframe and not in a new window / tab etc.以及验证您尝试访问的元素不在 iframe 内,也不在新的 window / 选项卡等中。

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

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