首页 > 解决方案 > 无法使用 Python 在 Selenium Webdriver 中单击框

问题描述

我想在使用 Python 在 Selenium Webdriver 中进行测试时单击具有 24h 作为文本的框,但无法这样做。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:&quot;Lucida Grande&quot;, &quot;Lucida Sans Unicode&quot;, 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:&quot;Lucida Grande&quot;, &quot;Lucida Sans Unicode&quot;, 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 代码图像

标签: pythonhtmlselenium

解决方案


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

推荐阅读