【问题标题】:Selenium find dynamic element with dynamic pathSelenium 使用动态路径查找动态元素
【发布时间】:2019-06-26 13:53:51
【问题描述】:

我正在编写一个 selenium 程序来抓取登录后的网站。然而,除了占位符文本之外的所有内容都是动态的,包括 css 选择器、xpath 等。有没有办法在没有 Xpath 的情况下通过可见文本进行选择?

html sn-p:

<form class="un-form un-login-form "><div class="un-login-form__change-school form-group">Name<br><small>D-26871, Russellstr. 33</small><br><a>Schule wechseln</a></div><div class="form-group"><input type="text" value="" placeholder="Benutzer" id="732de780-8f7b-41f6-98ba-c73503c93fcc" class="form-control"></div><div class="form-group"><input type="password" value="" placeholder="Passwort" id="5d7bc08a-7301-4348-82f1-a16e9e657720" class="form-control"></div><div class="un-login-buttons un-login-form__buttons btn-group"><button type="submit" title="Login" class="btn btn-primary">Login</button></div><div class="un-login-form__links"><a>Passwort vergessen?</a><br></div></form>

我的代码:

paswd = driver.find_element_by_xpath("//input[@placeholder='Passwort']")

因此,由于 xpath 不同,我总是找不到错误,因为类都命名相同,因此无法聚焦元素

【问题讨论】:

    标签: python python-3.x selenium-webdriver xpath css-selectors


    【解决方案1】:

    由于id 是动态的,因此您可以使用其他属性,也可以使用以下任一Locator Strategies

    • 使用css_selector

      driver.find_element_by_css_selector("input.form-control[placeholder='Passwort']").send_keys("3agle")
      
    • 使用xpath

      driver.find_element_by_xpath("//input[@class='form-control' and @placeholder='Passwort']").send_keys("3agle")
      

    【讨论】:

    • 所以很遗憾我仍然遇到同样的错误。只是为了提供一个想法,这是 chrome 的完整 xpath: //*[@id="app"]/div/div[1]/div/section/section/div/div[1]/div/div[2 ]/div[1]/div[2]/form/div[2] 现在这是我的表单组会话之一的 xpath。但是每次下一个会话时都会发生这种变化: //*[@id="app"]/div/div[1]/div/section/section/div/div[1]/div/div[2]/div[ 1]/div[2]/form/div[2] 只是一个例子,所以第一个是 //*[@id="app"]/div/div[1]/div/section 而第二个是 / /*[@id="app"]/div/div[1]/div/section/
    【解决方案2】:

    请尝试 driver.findElement(By.tagName("")

    【讨论】:

      【解决方案3】:

      好的,现在这种 XPATH 为我做了://*[@placeholder='Benutzer']

      【讨论】:

      • 哦,奇怪的是,只有当我将鼠标悬停在用户名输入上并拖动窗口而不是按住它直到登录成功时才有效
      猜你喜欢
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多