My code:
driver = webdriver.Chrome()
driver.get(url)
value = driver.find_element_by_xpath("//*[name()='div' and @id='chartContainer']//*[name()= 'svg' and @style= 'position: absolute; z-index: 6;']//*[name()= 'g' and @font-size= '10pt]")
driver.quit()
print(value)
Error message: *
InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //[name()='div' and @id='chartContainer']//[name()= 'svg' and @style= 'position: absolute; z-index: 6;']//[name()= 'g' and @font-size= '10pt] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//[name()='div' and @id='chartContainer']//[name()= 'svg' and @style= 'position: absolute; z-index: 6;']//[name()= 'g' and @font-size= '10pt]' is not a valid XPath expression. (Session info: chrome=94.0.4606.81)
CodePudding user response:
'
is missing at last of your xPath
expression.
value = driver.find_element_by_xpath("//*[name()='div' and @id='chartContainer']//*[name()= 'svg' and @style= 'position: absolute; z-index: 6;']//*[name()= 'g' and @font-size= '10pt']")
But the above xPath
what you have written points to 6th svg
tag and the 6th g
tag.
You need to use either any one of the below xPath
to point 6th svg
and 4th g
tag.
//*[name()='div' and @id='chartContainer']//*[name()= 'svg' and @style= 'position: absolute; z-index: 6;']//*[name()= 'g' ][4]
Or
//*[name()='div' and @id='chartContainer']//*[name()= 'svg'][6]//*[name()= 'g' ][4]
CodePudding user response:
You can point to 6th svg and 4th g tag like that :
((//div[@id='chartContainer']//*[name()='svg'])[6]//*[name()='g'])[4]//*[name()='text']
In code :
value = driver.find_element_by_xpath("((//div[@id='chartContainer']//*[name()='svg'])[6]//*[name()='g'])[4]//*[name()='text']").text
print(value)
Please put some explicit waits as well before interaction.
Code trial 1 :
time.sleep(5)
value = driver.find_element_by_xpath("((//div[@id='chartContainer']//*[name()='svg'])[6]//*[name()='g'])[4]//*[name()='text']").text
print(value)
Code trial 2 :
value = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "((//div[@id='chartContainer']//*[name()='svg'])[6]//*[name()='g'])[4]//*[name()='text']"))).text
print(value)
Imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
PS : Please check in the dev tools
(Google chrome) if we have unique entry in HTML DOM
or not.
Steps to check:
Press F12 in Chrome
-> go to element
section -> do a CTRL F
-> then paste the xpath
and see, if your desired element
is getting highlighted with 1/1
matching node.