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

本文中的知识点:

  • python selenium库安装
  • firefox geckodriver的下载与安装
  • selenium+firefox使用代理
  • 进阶学习

搭建开发环境:

PS:安装了的同学可以跳过了接着下一步,没安装的同学还是跟着我的步骤走一遍

安装selenium库
pip install selenium
安装firefox geckodriver

这里要注意要配置系统环境,把firefox geckodriver解压后放到python路径的Scripts目录下,跟pip在一个目录下。
这里可以教大家一个查看python安装路径的命令

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

火狐浏览器

安装火狐官方浏览器


代码样例

以请求百度为例

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

firefox = webdriver.Firefox()
firefox.get('https://www.baidu.com/')
print(firefox.page_source)
firefox.close()
firefox.quit()

结果如下
在这里插入图片描述
在这里插入图片描述

使用代理
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

profile = webdriver.FirefoxProfile()
proxy = '42.51.13.68:16816'
ip, port = proxy.split(":")
port = int(port)
# 不使用代理的协议,注释掉对应的选项即可
settings = {
    'network.proxy.type': 1,  # 0: 不使用代理;1: 手动配置代理
    'network.proxy.http': ip,
    'network.proxy.http_port': port,
    'network.proxy.ssl': ip,  # https的网站,
    'network.proxy.ssl_port': port,
}
# 更新配置文件
for key, value in settings.items():
    profile.set_preference(key, value)
profile.update_preferences()


options = Options()
firefox = webdriver.Firefox(firefox_profile=profile, options=options)
firefox.get('http://dev.kdlapi.com/testproxy')
print(firefox.page_source)
firefox.close()
firefox.quit()
    

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

进阶学习

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值