最新版本的selenium已不再支持PhantomJS,使用时会直接报错:
UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead warnings.
warn('Selenium support for PhantomJS has been deprecated, please use headless '
中文意思是:selenium已经放弃PhantomJS,请使用火狐浏览器或者Chrome浏览器的无头模式(headless,即无界面模式)。
首先我们需要解决的selenium对火狐和Chrome浏览器的驱动支持问题,事实上以前并不存在驱动问题,随着浏览器版本的不断提高,才发生驱动问题。
Firefox驱动
火狐需要安装geckodriver,下载最新版geckodriver,将geckodriver.exef放在C:\Program Files (x86)\Mozilla Firefox目录下,并将其加入环境变量,若不加入环境变量,在运行时需要给出驱动所在目录。后面Chrome浏览器同样。代码demo如下:
from selenium import webdriver
def main():
profile=webdriver.FirefoxOptions()
profile.add_argument('-headless') #设置无头模式
driver = webdriver.Firefox(executable_path='C:\Program Files (x86)\Mozilla Firefox\geckodriver', firefox_options=profile) #前面给出路径
driver.get("https://www.qiushibaike.com/8hr/page/1/")
print(driver.page_source)
driver.close()
if __name__ == '__main__':
main()
Chrome驱动
可直接在这个地址下载Chrome驱动,下载时注意对应的版本号,我的Chrome浏览器是V70,选择2.45版本。
然后将chromedriver.exe文件放在谷歌浏览器安装目录C:\Program Files (x86)\Google\Chrome\Application下(其它路径也行),自行选择是否添加环境变量。Demo如下:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def main():
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\Google\Chrome\chromedriver', chrome_options=chrome_options)
driver.get("https://www.baidu.com")
print(driver.page_source)
driver.close()
if __name__ == '__main__': main()
模拟登陆豆瓣
下面我们就用配置好的selenium和浏览器来自动登陆豆瓣,该代码2019.2.12检验有效,如失效说明豆瓣已更改网页代码。
豆瓣首页如下:
首选项是手机验证码登录,我们使用帐号密码登陆,因此需要首先点击密码登陆,需用Xpath定位位置
帐号,密码,登陆按钮的位置也用同样方式确定
注意点:
这样定位后,模拟登陆豆瓣,会直接失败,显示
unable to lacote username
这是因为豆瓣登陆界面使用了框架,下图
我也是检测了好久才看到页面使用了框架(被自己菜到),因此需要先跳转到框架,否则会定位失败,这个故事告诉我们,动手之前最后先分析一下网页使用的技术。
最终代码如下:
from selenium import webdriver
from selenium.webdriver import ActionChains
import time
from selenium.webdriver.support.ui import WebDriverWait
path = 'C:\Program Files (x86)\Mozilla Firefox\geckodriver'
def main():
#profile=webdriver.FirefoxOptions()
#profile.add_argument('-headless') #设置无头模式
driver = webdriver.Firefox(executable_path= path)
driver.get("https://www.douban.com")
driver.switch_to.frame(driver.find_elements_by_tag_name('iframe')[0])
action = driver.find_element_by_xpath("/html/body/div[1]/div[1]/ul[1]/li[2]")
ActionChains(driver).move_to_element(action).click(action).perform()
#WebDriverWait(driver,10).until(lambda the_driver: the_driver.find_element_by_xpath("//*[@id='username']").is_displayed())
driver.find_element_by_xpath("//*[@id='username']").send_keys("帐号")
driver.find_element_by_xpath("//*[@id='password']").send_keys("密码")
driver.find_element_by_xpath("/html/body/div[1]/div[2]/div[1]/div[5]/a").click()
time.sleep(10)
driver.switch_to.default_content() # 退出frame,没有这一句不能生成屏幕快照
# 生成登陆后快照
driver.save_screenshot(u"douban.png")
driver.close()
if __name__ == '__main__':
main()
效果如下: