How take XPATH inside a iframe?

2019-07-31 11:21发布

问题:

Im trying to get the XPATH inside a iframe called "gadget_6"

i need the xpath of select div. Using selenium i do:

self.change_frame('__gadget_6') #Change to the correct iframe

after that, i try to do:

self.selec_orgvdc = self.driver.find_element(By.XPATH,'/html/body/div[5]/div/div/div/table/tbody/tr/td/div')

for posteriorly do:

self.selec_orgvdc.click

but i obtain the error:

InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression /html/body/div[5]/div/div/div/table/tbody/tr/td/div because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '/html/body/div[5]/div/div/div/table/tbody/tr/td/div' is not a valid XPath expression.

Someone can help me?

New modification:

self.change_frame('__gadget_6')
time.sleep(4)
self.logger.info("Buscando orgvdc")
#self.selec_orgvdc = self.driver.find_element(By.CSS_SELECTOR,'div.GN4Y2ATIMD table div.gwt-Label')
self.selec_orgvdc = self.driver.find_element(By.XPATH,'//div[5]/div/div/div/table/tbody/tr/td/div')
self.logger.info("Encontrado!")

回答1:

Hi to work with xpath inside iframe first you have to sitch your driver instance ti that iframe then only you can perform any action

1.To switch to an iframe plz do it like : driver.switchTo().frame("selfservice");

Also looking at your source code i can clearly see there is 2 (two) i frames

1.iframe id = __gadget_6 2.iframe id = selfservice

hence i can guess why its not working in your case cause you are switching to a wrong i frame

now try this xpath //*[@class='GN4Y2ATIMD']/div/div/div/table/tbody/tr/td/div to perform click this will surely work.



回答2:

XPath shouldn't include the /html/body. try this:

self.selec_orgvdc = self.driver.find_element(By.XPATH,'//div[5]/div/div/div/table/tbody/tr/td/div')

Note that this will be quite brittle. Even better would be to do something like this CSS:

self.selec_orgvdc = self.driver.find_element(By.CSS,'div.GN4Y2ATIMD table div.gwt-Label')