2015-06-19 113 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

没问题。我很高兴它有帮助。 –