完整的xpath不能计算python selenium中的正确字段

zzzyeukh  于 2023-01-09  发布在  Python
关注(0)|答案(3)|浏览(156)

我有一个以下的问题。在图片波纹管我想填补一些文字到第二(红色)领域。

我的代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains

def set_scraper():
    """Function kills running applications and set up the ChromeDriver."""
    options = webdriver.ChromeOptions()
    options.add_argument("--start-maximized")
    driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver", options=options)
    return driver

def main() -> None:
    """Main function that is call when the script is run."""
    driver = set_scraper()
    driver.get("https://nahlizenidokn.cuzk.cz/VyberBudovu/Stavba/InformaceO")

    pokus = driver.find_element(By.XPATH, '/html/body/form/div[5]/div/div/div/div[3]/div/fieldset/div[2]/div[2]/input[1]')
    
    driver.implicitly_wait(10)
    ActionChains(driver).move_to_element(pokus).send_keys("2727").perform()

问题是它将"2727"发送到第一个字段,而不是红色字段。尽管/html/body/form/div[5]/div/div/div/div[3]/div/fieldset/div[2]/div[2]/input[1]是第二个字段的完整xpath。请问您知道为什么吗?

y1aodyip

y1aodyip1#

可以使用XPath根据子元素中的唯一文本"Obec"定位父元素,然后定位适当的input元素。
在这里,我使用的是看起来不会改变的固定属性值。
下面的代码是有效的:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 10)

url = "https://nahlizenidokn.cuzk.cz/VyberBudovu/Stavba/InformaceO"
driver.get(url)

wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@class='fieldsetWrapper'][contains(.,'Obec')]//input[@type='text']"))).send_keys("2727")

结果是:

3zwtqj6y

3zwtqj6y2#

尝试以下选项

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

element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@title='Zadejte název obce']")))
element.send_keys("2727")
atmip9wb

atmip9wb3#

您可以使用下面的XPATH在第二个文本字段中输入文本:

driver.find_element(By.XPATH, ".//input[@name='ctl00$bodyPlaceHolder$vyberObec$txtObec']").send_keys("2727")
# clicking on the button
driver.find_element(By.XPATH, ".//input[@title='Vyhledat obec']").click()

相关问题