[英]Unable to click on a box in Selenium Webdriver using Python
我想在使用 Python 在 Selenium Webdriver 中进行测试时单击具有 24 小时文本的框,但无法这样做。 Python代码:
from selenium import webdriver
from PIL import Image
from selenium.webdriver.chrome.service import Service
import time
service = Service('/Users/XYZ/Desktop/Selenium/chromedriver.exe')
service.start()
driver = webdriver.Remote(service.service_url)
driver.get('example.com')
driver.maximize_window()
driver.find_element_by_name("ctl00$BodyContent$Username").send_keys("id")
driver.find_element_by_name("ctl00$BodyContent$Password").send_keys("pwd")
driver.find_element_by_id("ctl00_BodyContent_LoginButton").click()
driver.execute_script("document.body.style.zoom='75%'")
driver.execute_script("window.scrollTo(0, 225);")
time.sleep(3)## lets say 3 seconds
driver.find_element_by_xpath("//*[@id='highcharts-114']/svg/g[19]/text").click()
driver.save_screenshot("screenshot.png")
HTML 代码:
<g zIndex="7" states="[object Object]" style="cursor:default;text-align:center;" transform="translate(164,61)"><rect rx="0" ry="0" fill="url(#highcharts-114)" x="0.5" y="0.5" width="27" height="18" stroke-width="1" stroke="#cccccc"></rect><text x="2.1875" y="14" style="font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;font-size:12px;font-weight:bold;color:#4d4d4d;fill:#4d4d4d;" zIndex="1"><tspan x="2.1875">24h</tspan></text></g>
<rect rx="0" ry="0" fill="url(#highcharts-114)" x="0.5" y="0.5" width="27" height="18" stroke-width="1" stroke="#cccccc"></rect>
<text x="2.1875" y="14" style="font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;font-size:12px;font-weight:bold;color:#4d4d4d;fill:#4d4d4d;" zIndex="1">
<tspan x="2.1875">24h</tspan>
</text>
错误信息:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='highcharts-114']/svg/g[19]/text"}
框 HTML 代码图像
请提供完整代码。盲目的猜测是您的页面可能没有及时加载,因此元素不存在。有两种方法: 坏的:
time.sleep(3)## lets say 3 seconds
driver.find_element_by_xpath("//*[@id='highcharts-114']/svg/g[19]/text").click()
以及 selenium 提供的等待方法(推荐)。
wait = WebDriverWait(driver, 10)
inputBox = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='highcharts-114']//*[name()='svg']//*[name()='g'][19]//*[name()='text']")))
inputBox.click()
注意:请将以下导入添加到您的解决方案中
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.