python爬虫——selenium+chrome使用代理

先看下本文中的知识点:html

  • python selenium库安装
  • chrome webdirver的下载安装
  • selenium+chrome使用代理
  • 进阶学习

搭建开发环境:

PS:安装了的同窗能够跳过了接着下一步,没安装的同窗跟着个人步骤走一遍python

安装selenium库

pip install selenium

安装chrome webdirver

这里要注意要配置系统环境,把chrome webdirver解压后放到python路径的Scripts目录下,跟pip在一个目录下。 这里能够教你们一个查看python安装路径的命令linux

# windows系统,打开cmd
where python
# linux系统
whereis python

谷歌浏览器

注意谷歌浏览器的版本要>=7.9,由于以前下载的chrome webdirver是7.9版本的。浏览器就本身安装吧。web


代码样例

好的,如今咋们的环境都配置好了,写几行代码试下,以请求百度为例chrome

from selenium import webdriver
# 用webdriver的chrome浏览器打开
chrome = webdriver.Chrome()
chrome.get('https://www.baidu.com')
print(chrome.page_source)
chrome.quit() #退出

运行下,先会打开chrome浏览器,而后访问百度,在打印page信息,最后关闭浏览器 在这里插入图片描述 在这里插入图片描述windows

使用代理

使用代理IP去访问就得加一个参数了,代码以下api

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
# 代理IP,由快代理提供
proxy = '60.17.254.157:21222'
# 设置代理
chrome_options.add_argument('--proxy-server=%s' % proxy)
# 注意options的参数用以前定义的chrome_options
chrome = webdriver.Chrome(options=chrome_options)
# 百度查IP
chrome.get('https://www.baidu.com/s?ie=UTF-8&wd=ip')
print(chrome.page_source)
chrome.quit() #退出

运行下,结果如图 在这里插入图片描述 在这里插入图片描述浏览器


扩展

不想用谷歌浏览器啊,想用火狐怎么办。没问题啊,webdriver也支持火狐。看下webdriver的帮助文档bash

from selenium import webdriver
help(webdriver)

看下图,不止支持火狐firefox,谷歌chrome,ie,opera等等都支持的。 在这里插入图片描述学习

进阶学习

相关文章
相关标签/搜索