我想抓取网站中的广告,但其中很多都是动态的,而且它们是 DOM 对象。例如在 this snippet
我可以通过 Selenium 获取 iframe 标签,但我不能再进一步了。我认为这是因为 XPATH。在这种情况下,<html>
的 XPATH iframe 里面是 /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
关于selenium - 使用 Selenium 抓取 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49825722/