selenium使用代理爬取数据

这篇博客主要介绍了如何利用Python的Selenium与Firefox浏览器配合,通过设置http和https代理来爬取网页数据。同时,提到了通过拨号上网切换IP以避免IP被封的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代理

因为chrome的代理使用目前还有一些问题,所以本文全部用的Firefox

http协议

host = "127.0.0.1"
port = 9999
profile = webdriver.FirefoxOptions()
profile.set_preference('network.proxy.type', 1)
profile.set_preference('network.proxy.http', host)  # IP为你的代理服务器地址:如‘127.0.0.0’,字符串类型
profile.set_preference('network.proxy.http_port', port)  # PORT为代理服务器端口号:如,9999,整数类型
browser = webdriver.Firefox(options=profile)

https协议

host = "127.0.0.1"
port = 9999
profile = webdriver.FirefoxProfile()
profile.set_preference('network.proxy.type', 1)
profile.set_preference('network.proxy.http', "%s" % host)
profile.set_preference('network.proxy.http_port', port)
profile.set_preference('network.proxy.ssl', "%s" % host)
profile.set_preference('network.proxy.ssl_port', port)
profile.update_preferences()
browser = webdriver.Firefox(firefox_profile=profile)

拨号上网

还有一种情况就是可以通过拨号上网的方式实现不停地切换ip,从而防止ip地址被封。

# 先将网络断开
os.system('Rasdial 宽带连接 /DISCONNECT')
# 然后重新连接网络
os.system('Rasdial 宽带连接 宽带用户名 宽带密码')
# 判断网络是否重连成功
# 如果有网络,则res为0,否则为1
res = os.system('ping www.baidu.com')
if not res:
	print('网络重连成功')
else:
	print('网络重连失败')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值