Selenium Webdriver python XPath 不起作用



我正在尝试使用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

请让我知道去哪里看,谢谢。

你需要诱导 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")

你能试试以下方法吗?

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

应该适用于该输入。只是为了试错,在执行此操作之前尝试一小段等待。

新的Selenium版本不允许这样做。

尝试以下代码

from selenium.webdriver.common.by import By

然后将"find_element_by_xpath语句"更改为

mydriver.find_element(By.XPATH,'//[@id="username"]').send_keys("myusername")

您可以参考链接以了解更多信息

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

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

最新更新