網(wǎng)頁爬蟲 - Python+Selenium+PhantomJs爬蟲,如何取得新打開頁面的源碼?
問題描述
我在做一個(gè)python爬蟲,使用了selenium庫和phantomjs瀏覽器。我在一個(gè)網(wǎng)頁中觸發(fā)了一個(gè)click事件打開了一個(gè)新的網(wǎng)頁,然后我用browser.page_source得到的卻是原來那個(gè)網(wǎng)頁非新打開網(wǎng)頁的源碼,請(qǐng)問我該如何取得新打開頁面的源碼呢?
問題解答
回答1:如果鏈接打開了一個(gè)新標(biāo)簽頁的話,你的driver還是下默認(rèn)使用的還是當(dāng)前窗口,
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)
比如,如果你的瀏覽器有幾個(gè)標(biāo)簽頁,那么window_handles就保存了對(duì)應(yīng)這幾個(gè)標(biāo)簽頁對(duì)應(yīng)的實(shí)例對(duì)象,所以如果你當(dāng)前只打開了一個(gè)網(wǎng)頁,那么你新打開的頁面就是 window_handles[1]轉(zhuǎn)換到那個(gè)頁面后,再獲取源碼。
回答2:如果是在當(dāng)前窗口打開,有可能因?yàn)樾马撁孢€沒有加載完成,到時(shí)拿不到新頁面的url和數(shù)據(jù),這里可以使用等待,并設(shè)置一些條件,確保新頁面加載完成再進(jìn)行操作,代碼如下:
from selenium.webdriver.support.ui import WebDriverWait# 等待新頁面生成WebDriverWait(self.browser, 5).until( expected_conditions.presence_of_element_located((By.ID, 'username') )
