Technology Sharing

Python cannot locate elements when using selenium web page simulation solution 1

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

When simulating a web page, sometimes we can copy the xpath of an element, but cannot click on the element using selenium's xpath click. There are several reasons for this situation. This article will describe one of them - iframe

For example, in the URL below, if an iframe appears in the second line, the elements in the following lines cannot be located. At this time, we need to switch to iframe mode
insert image description here

The code is as follows. You need to use switch_to.frame(). The () refers to the number of iframe tags in the entire web page. The first one is 0, which everyone knows. It is recommended to search in the web page source code
After completion, switch_to.default_content() exits iframe editing. There is no need to fill in the ().

from selenium.webdriver import Chrome
web = Chrome()

#进入iframe编辑
web.switch_to.frame(2) #第3个iframe标签
time.sleep(1)
#定位到元素
web.find_element(By.XPATH,'//*[@id="root"]/div/div[1]/div[2]/div[1]').click() #点击元素
web.switch_to.default_content()#退出iframe
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9