【问题标题】:NameError: name 'btn' is not defined while find element by XPATH using SeleniumNameError: name 'btn' is not defined while find element by XPATH using Selenium
【发布时间】:2018-12-19 01:32:22
【问题描述】:

从 chrome 元素检查器复制的 Xpath 和选择器信息:

<button class="btn btn-white btn--no-margin btn--full-width _1XvaFLD3_IpAQNG-OJU2-H _1xNlj_ScH8hEMWzrkRt1A">Sign up</button>

CssSelector:

#main > div > div.Root__top-container.Root__top-container--has-notice-bar > div.Root__nav-bar.Root__nav-bar--has-notice-bar > nav > div.navBar-signupPrompt._3nonY0buM5Z1AF4aRrP8VY > p:nth-child(1) > button

我试图找到的:

button = wd.find_element(By.XPATH("//button[contains(text(),'"+btn-white+"')]"))

返回错误为:

NameError: name 'btn' is not defined

我找到了this,它告诉我如何通过部分名称进行查找。

任何帮助将不胜感激。

【问题讨论】:

    标签: python selenium selenium-webdriver xpath


    【解决方案1】:

    btn-whitebutton 元素中的一个类,而不是文本。而且你不能用它作为变量它需要是str参数

    button = wd.find_element_by_class_name('btn-white')
    

    或者

    button = wd.find_element(By.CLASS_NAME, 'btn-white')
    

    如果你想通过Sign up文字定位

    button = wd.find_element(By.XPATH, '//button[.="Sign up"]')
    

    【讨论】:

    • 谢谢!仅供参考,最后一个解决方案“通过“注册”文本定位返回错误:selenium.common.exceptions.WebDriverException:消息:未知错误:“使用”必须是字符串。有什么想法吗??
    • @GregIven 尝试使用单括号 wd.find_element(By.XPATH, '//button[.="Sign up"]')
    【解决方案2】:

    尝试:

    wd.find_element(By.XPATH("//button[contains(text(),'Sign up')]"))
    

    【讨论】:

      【解决方案3】:

      它对你更有效吗?

      button = wd.find_element(By.XPATH("//button[text()='Sign up']"))
      

      【讨论】:

        猜你喜欢
        • 2022-12-02
        • 2013-04-09
        • 1970-01-01
        • 2021-01-03
        • 1970-01-01
        • 2020-11-07
        • 2017-01-09
        • 2017-06-14
        相关资源
        最近更新 更多