使用硒抓取iframe



我想在网站上抓取广告,但其中许多是动态的,它们是 DOM 对象。例如在此代码段

我可以通过Selenium获得iframe标签,但我不能再进一步了。我认为这是因为XPATH。在这种情况下,iframe 内<html>的 XPATH 是/html与主页<html>相同。

这是使用的代码行:

element = WebDriverWait(self.driver,20).until(EC.presence_of_all_elements_located((By.XPATH, '/html')))

有什么建议吗?

默认情况下,selenium.webdriver 对象设置为它已解析的默认页面。要获取iframe数据,您必须切换到给定的iframe。

driver = webdriver.Chrome(executable_path=path_chrome)
# find the frame using id, title etc.
frame = driver.find_elements_by_xpath("//iframe[@title='iframe_to_get']")
# switch the webdriver object to the iframe.
driver.switch_to.frame(frame[i])

永远记住,如果迭代iframe,然后切换回默认网页。否则,您将无法切换到同一代码中的其他 iframe。

driver.switch_to.default_content()

更新

下面提到的函数现已弃用。所以我更新了答案。

driver.switch_to_frame('Any frame') #deprecated
driver.switch_to_default_content() #deprecated

要在页面上切换到 iframe,您应该使用 driver.switch_to.frame

iframeElement = driver.find_element_by_tag_name('iframe')
driver.switch_to.frame(iframeElement)

现在,您可以使用driver在 iframe 中查找元素。

要切换回 iframe,请使用driver.switch_to_default_content()

最新更新