我在網站上有條形圖,需要點擊它。使用開發人員工具,我低于 xpath:
/html/body/root/main/portal/div[2]/div/div/div/my-portal/div[3]/td-tyr/td-tyr/div[1]/filter-bar/div/div[3]/div[1]/div[1]/bar-chart/div/div[1]/div/svg/g[4]/g[1]/rect[1]
在 xpath 中使用上述內容時,它給出了無效的運算式。任何幫助將不勝感激。
uj5u.com熱心網友回復:
要單擊條形圖,因為元素具有父<svg>元素,您可以使用以下任一定位器策略:
使用
css_selector:driver.find_element(By.CSS_SELECTOR, "bar-chart svg g rect.highcharts-point.highcharts-color-0.highcharts-point-hover[x='31.5'][y='40.5']").click()使用
xpath:driver.find_element(By.XPATH, "//bar-chart//*[name()='svg']//*[name()='g']//*[name()='rect'][@x='31.5' and @y='40.5']").click()
理想的情況下到上點擊可點擊元素,你需要引起WebDriverWait的element_to_be_clickable(),你可以使用以下的定位策略:
使用
CSS_SELECTOR:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "bar-chart svg g rect.highcharts-point.highcharts-color-0.highcharts-point-hover[x='31.5'][y='40.5']"))).click()使用
XPATH:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//bar-chart//*[name()='svg']//*[name()='g']//*[name()='rect'][@x='31.5' and @y='40.5']"))).click()注意:您必須添加以下匯入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
參考
您可以在以下位置找到一些關于與 SVG 元素互動的相關討論:
- 如何通過 Selenium-Python 訪問“rect”型別元素
- 使用 selenium python 點擊?? svg
uj5u.com熱心網友回復:
基本上有 4 種方法可以在 Selenium 中單擊。
我將使用這個 xpath
//rect[@class='highcharts-point highcharts-color-0 highcharts-point-hover'][@stroke='#ffffff']
代碼試用1:
time.sleep(5)
driver.find_element_by_xpath("//rect[@class='highcharts-point highcharts-color-0 highcharts-point-hover'][@stroke='#ffffff']").click()
代碼試用2:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//rect[@class='highcharts-point highcharts-color-0 highcharts-point-hover'][@stroke='#ffffff']"))).click()
代碼試用3:
time.sleep(5)
button = driver.find_element_by_xpath("//rect[@class='highcharts-point highcharts-color-0 highcharts-point-hover'][@stroke='#ffffff']")
driver.execute_script("arguments[0].click();", button)
代碼試用4:
time.sleep(5)
button = driver.find_element_by_xpath("//rect[@class='highcharts-point highcharts-color-0 highcharts-point-hover'][@stroke='#ffffff']")
ActionChains(driver).move_to_element(button).click().perform()
進口:
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.webdriver.common.action_chains import ActionChains
PS:請檢查dev tools(谷歌瀏覽器)我們是否有唯一的條目HTML DOM。
檢查步驟:
Press F12 in Chrome- >去element節- >做一個CTRL F- >再貼上xpath看看,如果你需要的element是越來越強調與1/1匹配的節點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/372305.html
下一篇:帶有影像和填充的SVG剪切路徑
