首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Selenium使用代理IP&无头模式访问网站

Selenium使用代理IP&无头模式访问网站

作者头像
py3study
发布2020-01-07 16:18:44
3K0
发布2020-01-07 16:18:44
举报
文章被收录于专栏:python3python3

Selenium使用代理IP&无头模式访问网站

很多防爬机制会自动检测ip访问的频率,超过设定的次数,就会被封,这个时候就需要使用代理ip来解决这个问题了

代码如下:

#!/usr/bin/env python
# coding: utf-8
from selenium import webdriver


class Proxy(object):
    def __init__(self):
        self.proxy_ip = 'http://代理ip地址:端口'
        self.browser = self.getbrowser()
        self.getpage(self.browser)

    def getbrowser(self):
        options = webdriver.ChromeOptions()
        # 设置代理
        desired_capabilities = webdriver.DesiredCapabilities.INTERNETEXPLORER.copy()
        desired_capabilities['proxy'] = {
            "httpProxy": self.proxy_ip,
            # "ftpProxy": self.proxy_ip,  # 代理ip是否支持这个协议
            # "sslProxy": self.proxy_ip,  # 代理ip是否支持这个协议
            "noProxy": None,
            "proxyType": "MANUAL",
            "class": "org.openqa.selenium.Proxy",
            "autodetect": False
        }
        # 使用无头模式
        options.add_argument('headless')
        browser = webdriver.Chrome(chrome_options=options,
                                   executable_path=r'D:\chromedriver_2.41\chromedriver.exe',
                                   desired_capabilities=desired_capabilities)
        return browser

    def getpage(self, browser):
        # 打开目标网站
        browser.get("https://www.baidu.com")
        # 对整个页面进行截图
        browser.save_screenshot('百度.png')
        # 打印网站的title信息
        print(browser.title)

        # 检测代理ip是否生效
        browser.get("http://httpbin.org/ip")
        # 获取当前所有窗口集合(list类型) --- 因为打开多个窗口
        handles = browser.window_handles
        # 切换到最新的窗口
        browser.switch_to_window(handles[-1])
        # 打印新窗口网页的内容
        print(browser.page_source)


if __name__ == '__main__':
    Proxy()

运行程序,显示打印的是代理ip地址,则表示使用代理成功

blob.png
blob.png

还会自动截图

blob.png
blob.png
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-08-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档