day4 Python的selenium库

一  介绍

# selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题。

# selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等,来拿到网页渲染之后的结果,可支持多种浏览器。主要利用它来跳过登录验证

from selenium import webdriver

# 谷歌浏览器
browser=webdriver.Chrome()
# 火狐浏览器
browser=webdriver.Firefox()
# 无界面浏览器
browser=webdriver.PhantomJS()
# 苹果浏览器
browser=webdriver.Safari()
# IE浏览器
browser=webdriver.Edge()

二  安装

# 安装:selenium+chromedriver
pip3 install selenium
下载chromdriver.exe放到python安装路径的scripts目录中即可,注意最新版本是2.38,并非2.9
国内镜像网站地址:http://npm.taobao.org/mirrors/chromedriver/2.38/
最新的版本去官网找:https://sites.google.com/a/chromium.org/chromedriver/downloads

#验证安装
C:\Users\Administrator>python3
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from selenium import webdriver
>>> driver=webdriver.Chrome() #弹出浏览器
>>> driver.get('https://www.baidu.com')
>>> driver.page_source

#注意:
selenium3默认支持的webdriver是Firfox,而Firefox需要安装geckodriver
下载链接:https://github.com/mozilla/geckodriver/releases
 

selenium+chromedriver

 下载selenium请求库也可以直接在Pycharm进行

  可以修改下载源为清华源

    -D:\python36\Lib\site-packages\pip\models\index.py

    -PyPI = index('https://pypi.tuna.tsinghua.edu.cn/simple')

三  使用程序来启动谷歌浏览器

from selenium import webdriver
import time
driver = webdriver.Chrome()#直接去Script文件夹中查找驱动
#driver = webdriver.Chrome(r'c:\Users\Dell\Downloads\chromedriver.exe')#  填写驱动路径
time.sleep(5)#启动谷歌浏览器五秒
driver.close()#开启时间满足后自动关闭浏览器

猜你喜欢

转载自www.cnblogs.com/zhenwu/p/11099890.html