代码之家  ›  专栏  ›  技术社区  ›  Kunal

Selenium Webdriver python XPath不工作

  •  1
  • Kunal  · 技术社区  · 8 年前

    我正在尝试使用Python和selenium webdriver自动化一个过程。 我能够成功登录并导航到我想要发布内容的页面,但由于某些原因,系统无法识别xpath。

    它给出以下错误:

    NoSuchElementException:无法定位元素://*[@id=“widecol”]/div/form/p[1]/input

    这是我的代码:

    from selenium import webdriver
    mydriver = webdriver.Firefox()
    mydriver.get("https://www.phishtank.com/")
    mydriver.maximize_window()
    mydriver.find_element_by_xpath('//*[@id="username"]').send_keys("myusername")
    mydriver.find_element_by_xpath('//*[@id="password"]').send_keys("mypassword")
    mydriver.find_element_by_xpath('//*[@id="header"]/div[2]/form/input[3]').click()
    mydriver.find_element_by_xpath('//*[@id="nav"]/ul/li[2]/a').click()
    mydriver.find_element_by_xpath('//*[@id="widecol"]/div/form/p[1]/input').send_keys("sample text testing to fill form")
    

    这是我的HTML代码

    <div id="widecol">
    <div class="padded">
        <form method="POST">
        <h2>Add A Phish</h2>
        <ol>
            <li>Visit our <b><a href="what_is_phishing.php">What is phishing?</a></b> page to confirm that the suspected phish meets all of the criteria.</li>
            <li>Add a phish using the form below, or even better, submit a phish directly <a href="mailto:phish@phishtank.com">via email</a>.</li>
        </ol>
        <h3>Phish URL:</h3>
                <p>
                <input type="text" name="phish_url" style="width:90%;" value="" /><br />
                <span class="small">Copy and paste the URL of the phishing website.</span>
        </p>
        <h3>What is the organization referenced in the email?</h3>
                <p class="slim">
            <select name="phish_target">
    

    这给了我以下错误:

    NoSuchElementException:无法定位元素://*[@id=“widecol”]/div/form/p[1]/input

    以下是HTML代码:

    <input type="text" name="phish_url" style="width:90%;" value=""> outer HTML code
    

    这是我的XPath:

    //*[@id="widecol"]/div/form/p[1]/input - Xpath
    

    请告诉我去哪里找,谢谢。

    3 回复  |  直到 8 年前
        1
  •  1
  •   undetected Selenium    8 年前

    你需要诱导 WebDriverWait 对于要单击的元素,可以使用以下代码行:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='phish_url' and @type='text']"))).send_keys("sample text testing to fill form")
    
        2
  •  0
  •   Ayoub_B    8 年前

    没有完整的HTML,我们无法判断XPath是否正确。 你能尝试包含更多的外部Html代码吗?

    您可以尝试在单击最后一个URL后等待,可能该元素尚未加载。 您还可以检查输入是否在iframe中,这可能是导致问题的原因。

        3
  •  0
  •   Anand    8 年前

    你能试试下面的方法吗?

    //*[@id='widecol']//input[@name='phish_url']
    

    应该适用于该输入。为了试验/错误起见,请在执行此操作之前尝试一小段等待时间。

    推荐文章