Python+Selenium+PhantomJs爬虫 怎么抓取弹出新标签页的内容,seleniumphantomjs,我在做一个python爬


我在做一个python爬虫,使用了selenium库和phantomjs浏览器。我在一个网页中触发了一个click事件打开了一个新的网页,然后我用browser.page_source得到的却是原来那个网页非新打开网页的源码,请问我该如何取得新打开页面的源码呢?

如果是在当前窗口打开,有可能因为新页面还没有加载完成,到时拿不到新页面的url和数据,这里可以使用等待,并设置一些条件,确保新页面加载完成再进行操作,代码如下:

from selenium.webdriver.support.ui import WebDriverWait# 等待新页面生成WebDriverWait(self.browser, 5).until(    expected_conditions.presence_of_element_located((By.ID, "username")    )

如果链接打开了一个新标签页的话,你的driver还是下默认使用的还是当前窗口,

Alternatively, you can pass a “window handle” to the “switch_to_window()” method. Knowing this, it’s possible to iterate over every open window like so:

for handle in driver.window_handles:    driver.switch_to_window(handle)

比如,如果你的浏览器有几个标签页,那么window_handles就保存了对应这几个标签页对应的实例对象,所以如果你当前只打开了一个网页,那么你新打开的页面就是 window_handles[1]
转换到那个页面后,再获取源码。

编橙之家文章,

评论关闭