如何使用 Python 在 Selenium 中处理框架?
我们可以使用 Selenium 处理框架。框架是一个 HTML 元素,它可以在页面中的另一个文档内保留一个文档。HTML 使用 <frame> 或 <iframe> 标签在文档内嵌入框架。
Selenium 中有多个可用于处理框架的 API。它们列在下面 -
switch_to_frame(id)
此方法用于使用框架 ID 识别框架,然后将焦点切换到该特定框架。
语法 -
driver.switch_to_frame("frameid"), where frameid is the id attribute present under the frame/iframe tag in HTML.
switch_to_frame(name)
此方法用于使用框架名称识别框架,然后将焦点切换到该特定框架。
语法 -
driver.switch_to_frame("framename"), where framename is the name attribute present under the frame/iframe tag in HTML.
switch_to_frame(webelement)
此方法用于使用框架 Web 元素识别框架,然后将焦点切换到该特定框架。
语法 -
driver.switch_to_frame("frameclassname"), where frameclassname is the name of class attribute present under the frame/iframe tag in HTML.
switch_to_parent_frame()
此方法用于退出当前框架,然后我们可以访问框架外部的元素,而不是框架内部的元素。
switch_to_default_content()
此方法用于退出所有框架并将焦点切换到页面。一旦我们退出,就会失去对页面中框架内元素的访问权限。
示例
带框架的代码实现。
from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://the-internet.herokuapp.com") #to refresh the browser driver.refresh() driver.find_element_by_link_text("Frames").click() driver.find_element_by_link_text("Nested Frames").click() # to switch to frame with frame name driver.switch_to.frame("frame-bottom") # to get the text inside the frame and print on console print(driver.find_element_by_xpath ("//*[text()='BOTTOM']").text) # to move out the current frame to the page level driver.switch_to.default_content() #to close the browser driver.quit()
广告