2015-06-19 84 views
1
from selenium import webdriver 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.common.exceptions import NoSuchElementException 
from selenium.webdriver.common.keys import Keys 
from bs4 import BeautifulSoup 

driver = webdriver.PhantomJS() 
#driver = webdriver.Firefox() 
driver.get('http://global.ahnlab.com/site/securitycenter/securityinsight/securityInsightList.do') 
driver.execute_script("getView('2218')") 

html_source = driver.page_source 
driver.quit() 

soup = BeautifulSoup(html_source) 

print(soup.h1.string) 

當我使用Firefox()時,結果是[AhnLab將外觀置於第4個直年的RSAConference],我想要的。 但是當我使用PhanthomJS()時,結果是我不想要的[Security Insight]。execute_script()在python中無法使用phantomjs

如果我使用PhantomJS(),我無法得到我想要的結果? 我想用無頭瀏覽器得到第一個結果。

謝謝。

+0

我的答案是否適合您? –

回答

3

phantomjs驅動程序不立即在javascript調用之後加載導航。只需在JavaScript調用之後進行5-10秒的睡眠,它就可以爲您工作。

import time 

from selenium import webdriver 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.common.exceptions import NoSuchElementException 
from selenium.webdriver.common.keys import Keys 
from bs4 import BeautifulSoup 

driver = webdriver.PhantomJS() 
#driver = webdriver.Firefox() 
driver.get('http://global.ahnlab.com/site/securitycenter/securityinsight/securityInsightList.do') 
driver.execute_script("getView('2218')") 

# Introduce a sleep of 5 seconds here 
time.sleep(5) 

html_source = driver.page_source 
driver.quit() 

soup = BeautifulSoup(html_source) 

print(soup.h1.string) 
+0

謝謝,它的工作原理! – paul

+0

沒問題。我很高興它有幫助。 –