Python 无法使用ID和xpath定位元素
我找不到按钮 我想通过使用按钮“Dodaj”来检查是否出现警报,将101个项目添加到购物篮中Python 无法使用ID和xpath定位元素,python,selenium,selenium-chromedriver,Python,Selenium,Selenium Chromedriver,我找不到按钮 我想通过使用按钮“Dodaj”来检查是否出现警报,将101个项目添加到购物篮中 <div class="input-group input-group-sm"> <span class="input-group-btn"> <button id="add-product-5e9847b5ee071" class="btn btn-sm" role="button" data-add-to-basket="" data-pr
<div class="input-group input-group-sm">
<span class="input-group-btn">
<button id="add-product-5e9847b5ee071" class="btn btn-sm" role="button" data-add-to-basket="" data-product-price="15.54" data-product-name="Okulary">Dodaj</button>
</span>
<input type="number" min="0" step="1" class="form-control" value="0" autocomplete="off">
</div>
还有ID“add-product-5e9847b5ee071”,但我收到消息:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="add-product-5e9847b5ee071"]"}
有人能告诉我怎么回事吗?请注意,虽然每个product Dodaj按钮都有一个唯一的id发生变化,但它们都具有与容器对应的相同属性数据product name。例如,对于Piłka,如果需要Dodaj按钮,可以使用以下命令
elem = driver.find_elements_by_xpath('//button[@data-product-name="Piłka"]')
输入数据后单击第一个
Dodaj
按钮
WebDriverWait
()并等待元素可点击
()并跟随xpath
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
driver=webdriver.Chrome()
driver.get("https://buggy-testingcup.pgs-soft.com/task_1")
inputtext=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"(//input[@class='form-control'])[1]")))
inputtext.clear()
inputtext.send_keys("101")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"(//button[text()='Dodaj'])[1]"))).click()
还有一个xpath选项
driver=webdriver.Chrome()
driver.get("https://buggy-testingcup.pgs-soft.com/task_1")
inputtext=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//h4[text()='Okulary']/following::input[1]")))
inputtext.clear()
inputtext.send_keys("101")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//h4[text()='Okulary']/following::button[1]"))).click()
浏览器快照:
假设您在正确的页面上,为什么不尝试add=self.driver。也可以通过_id(“add-product-5e9847b5ee071”)查找_元素,因为add product-####之后有一个唯一的字符串,也许可以确保该值不会更改,并且正确反映您想要的内容。我尝试过,但这也不起作用。我写道我还使用了Id.selenium.common.exceptions.NoSuchElementException:Message:没有这样的元素:找不到元素:{“方法”:“css选择器”,“选择器”:“[Id=”add-product-5e9847b5ee071”]”}如果页面刷新,则添加产品后的字母数字字符串将更改按钮。这就是找不到元素的原因。
driver=webdriver.Chrome()
driver.get("https://buggy-testingcup.pgs-soft.com/task_1")
inputtext=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//h4[text()='Okulary']/following::input[1]")))
inputtext.clear()
inputtext.send_keys("101")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//h4[text()='Okulary']/following::button[1]"))).click()