【问题标题】:Python Selenium: Difficulty finding the password elementPython Selenium:难以找到密码元素
【发布时间】:2019-03-07 08:47:45
【问题描述】:

我第一次尝试使用 Selenium 以自动方式登录网站。我可以使用以下代码轻松找到电子邮件(作为用户名)元素:

但是,对于密码,没有 id 或 name 标签,所以我很难找到那个元素。这是页面的源代码。密码元素在下面以灰色突出显示:

我尝试使用以下语句通过 link_text 和 class_name 定位密码元素,但均失败:

我想通过 XPath 定位可能是这里的方法,但我不确定语法(特别是因为有这么多 div 标签)。感谢您提供任何帮助。

【问题讨论】:

  • 请将 html 和代码发布为文本,而不是图像。
  • 有一种简单的方法可以使用 google chrome 获取 XPATH,在开发者工具中只需单击右键单击该元素并选择复制 XPATH,
  • 谢谢!在开发人员工具中复制 xpath 后,我能够使用 xpath 执行此操作。

标签: python selenium selenium-webdriver web-scraping selenium-chromedriver


【解决方案1】:

request.passwordng-model 属性,而不是文本。

find_element_by_class_name 接收一堂课,你尝试了三堂课。

使用css_selector 定位元素:

request.password

driver.find_element_by_css_selector('[ng-model="request.password"]')

按班级

driver.find_element_by_css_selector('.form-control.ng-pristine.ng-valid')

【讨论】:

    【解决方案2】:

    假设页面上没有其他密码元素,一种方法是找到所有输入标签,然后将它们过滤到密码字段中。

    def getPassword(driver):
        inputs = driver.find_elements_by_tag_name('input')
        for input in inputs:
            if input.get_attribute('type')=='password':
                return input
        return None
    

    Got syntax help from this question

    【讨论】:

      【解决方案3】:

      最好的办法是

      driver.findElement(By.xpath("//input[@type='password'][@title='Password']")) 
      

      尝试使用较少的类选择器并使用 id 或标签。类可以与另一个元素相关联。这是Java,对不起。如果需要,可以在 python 中找到它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-29
        • 1970-01-01
        • 2021-12-17
        • 2018-11-07
        • 2019-06-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多