Py学习  »  Python

Python/Selenium get_元素问题

weakhandjoe • 3 年前 • 1316 次点击  

我试图用python登录网页,但由于某种原因,无论我怎么尝试,我都无法获得正确的登录元素,因为我是noob,这是我的第一次尝试。

这应该是网页中的元素:

<label class="">Username</label>
<input type="text" formcontrolname="username" class="form-control ng-pristine ng-invalid ng-touched xh-highlight">

我尝试过按标签搜索,但没有成功:

username = browser.find_element_by_xpath("//label[contains(text(),'Username')]")

我尝试过按类别搜索:

username = browser.find_element_by_xpath('//input[@class="form-control ng-pristine ng-invalid ng-touched"]')

我尝试过使用CssSelector进行搜索:

username = browser.find_element_by_css_selector("input[formcontrolname='Username']")

我甚至试过全路:

username = browser.find_element_by_xpath("/html/body/app/div[@class='app-container']/ng-component/div[@class='container']/div[@class='row']/div[@class='col']/div[@class='card']/ng-component/div[@class='card-body']/form[@class='ng-pristine ng-invalid ng-touched']/div[@class='form-group'][1]/input[@class='form-control ng-pristine ng-invalid ng-touched']")

我不知道我做错了什么,请帮忙

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129441
文章 [ 2 ]  |  最新文章 3 年前
Prophet
Reply   •   1 楼
Prophet    3 年前

有几个可能的问题:

  1. 在尝试访问元素之前,您可能错过了让页面加载的等待/延迟。
  2. 元素可能位于iframe内部,因此必须切换到该iframe才能访问其中的元素。
  3. 定位器可能不是唯一的。
    为了给出更清晰的答案,我们需要查看您正在使用的we页面以及所有相关代码
undetected Selenium
Reply   •   2 楼
undetected Selenium    3 年前

找到 可点击 你需要诱导的元素 WebDriverWait 对于 element_to_be_clickable() 您可以使用以下任一选项 Locator Strategies :

  • CSS_选择器 :

    username = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[formcontrolname='username']"))).click()
    
  • 使用 XPATH :

    username = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@formcontrolname='username']"))).click()
    
  • :您必须添加以下导入:

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