Python + selenium + chrome uses the user name and password authorization of agent auth

Sunshine island Master 2020-11-13 10:32:28
python selenium chrome uses user


MIPO agent , Global leading agency brand , Focus on the agency industry for nearly ten years , Provide open 、 Private 、 Exclusive agent , And you can try it for free

MIPO agent official website :https://proxy.mimvp.com

 

An example of this article , It's a combination of MIPO's agent's privacy 、 exclusive 、 Open agent , Examples of specialized research and development ,

Support http、https No password for 、 White list ip、 There are three types of password authorization

 

Example , The plug-in used xpi succeed in inviting sb. MIPO agent official website , Or MIPO official  github  download

this paper , Give the complete code directly , All have been strictly verified and passed , Please refer to the notes for details

 

The running environment of the example in this article :

MacBook Pro  MacOS High Sierra Version 10.13.4

Google Chrome  Version 63.0.3239.84 (Official Build) (64-bit)

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 12:39:47) 

$ pip list | grep selenium
selenium (3.4.2)

 

chromedriver Download address ://chromedriver.storage.googleapis.com/index.html

 

Python + Selenium + Chrome

Error hint :WebDriverException: 'chromedriver' executable needs to be in PATH

resolvent :

a.  download  ChromeDriver, For other browsers, see Website shows

b. Copy  chromedrive  File to Google Chrome Program directory , Or copy it to the environment variable

cp chromedrive /usr/local/bin/

The location path in each operating system can refer to official Wiki

Python Create... In the code webdriver Object  chromedrive  route

Example 1:MacOS + chrome Environmental Science

1

2

3

4

5

chromedriver = "/Applications/Google Chrome.app/Contents/MacOS/chromedriver"

browser = webdriver.Chrome(executable_path=chromedriver)        # open Chrome browser

browser.get(url)    

content = browser.page_source

print("content: " + str(content))

 

Example 2:MacOS + environment variable

1

2

3

4

5

6

7

8

9

10

11

12

13

14

def spider_url_chrome(url):

    browser = None

    display = None

    try:

        display = Display(visible=0, size=(800, 600))

        display.start()

        chromedriver = '/usr/local/bin/chromedriver'

        browser = webdriver.Chrome(executable_path=chromedriver)        # open Chrome browser

        browser.get(url)    

        content = browser.page_source

        print("content: " + str(content))

    finally:

        if browser: browser.quit()

        if display: display.stop()

 

Selenium + chromedriver Proxy usage , No password or white list set ip

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

## webdriver + chrome + proxy + whiteip ( password-less , Or the white list ip to grant authorization )

## MIPO agent :https://proxy.mimvp.com

def spider_url_chrome_by_whiteip(url):

    browser = None

    display = None

     

    ## White list ip, Please see the MIPO agent member center : https://proxy.mimvp.com/usercenter/userinfo.php?p=whiteip

    mimvp_proxy = {

                    'ip'            : '140.143.62.84',      # ip

                    'port_https'    : 62288,                # http, https

                    'port_socks'    : 62287,                # socks5

                    'username'      : 'mimvp-user',

                    'password'      : 'mimvp-pass'

                  }

     

    try:

        display = Display(visible=0, size=(800, 600))

        display.start()

         

        chrome_options = Options()                      # ok

        chrome_options = webdriver.ChromeOptions()      # ok

        proxy_https_argument = '--proxy-server=http://{ip}:{port}'.format(ip=mimvp_proxy['ip'], port=mimvp_proxy['port_https'])     # http, https ( password-less , Or the white list ip to grant authorization , success )

        chrome_options.add_argument(proxy_https_argument)

#         proxy_socks_argument = '--proxy-server=socks5://{ip}:{port}'.format(ip=mimvp_proxy['ip'], port=mimvp_proxy['port_socks'])   # socks5 ( password-less , Or the white list ip to grant authorization , Failure )

#         chrome_options.add_argument(proxy_socks_argument)

         

        chromedriver = '/usr/local/bin/chromedriver'

        browser = webdriver.Chrome(executable_path=chromedriver, chrome_options=chrome_options)        # open Chrome browser

        browser.get(url)    

        content = browser.page_source

        print("content: " + str(content))

    finally:

        if browser: browser.quit()

        if display: display.stop()

 

 

Selenium + chromedriver Proxy usage , Support http、https Account and password

This example , The user name and password authorization of MIPO agent is adopted

Access to account name and password Authorization , Please go to MIPO agent - Membership Center -  White list ip

1、 Create a zip package , Contains the following two files  background.js and  manifest.json, Pack it up proxy.zip

1)background.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

var config = {

    mode: "fixed_servers",

    rules: {

      singleProxy: {

        scheme: "http",

        host: "140.143.62.84",

        port: 19480

      },

      bypassList: ["mimvp.com"]

    }

  };

 

chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});

 

function callbackFn(details) {

    return {

        authCredentials: {

            username: "mimvp-user",

            password: "mimvp-pass"

        }

    };

}

 

chrome.webRequest.onAuthRequired.addListener(

        callbackFn,

        {urls: ["<all_urls>"]},

        ['blocking']

);</all_urls>

Be careful : In the above configuration , Need to put the agent ip、port、username、password Replace it with MIPO's agent ip:port、 Authorized user name and password

 

2)manifest.json

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

{

    "version": "1.0.0",

    "manifest_version": 2,

    "name": "Chrome Proxy",

    "permissions": [

        "proxy",

        "tabs",

        "unlimitedStorage",

        "storage",

        "<all_urls>",

        "webRequest",

        "webRequestBlocking"

    ],

    "background": {

        "scripts": ["background.js"]

    },

    "minimum_chrome_version":"22.0.0"

}

explain : The above configuration , No need to change , Copy directly and use it

 

2、 add to proxy.zip To chrome As a plug-in

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

#!/usr/bin/env python

# -*- coding:utf-8 -*-

 

from selenium import webdriver

from selenium.webdriver.common.proxy import *

from selenium.webdriver.chrome.options import Options

from pyvirtualdisplay import Display

# from xvfbwrapper import Xvfb

 

 

def spider_url_chrome_by_https(url):

    browser = None

    display = None

    try:

        display = Display(visible=0, size=(800, 600))

        display.start()

         

        chrome_options = Options()

        chrome_options.add_extension("proxy.zip")

         

        chromedriver = '/usr/local/bin/chromedriver'

        browser = webdriver.Chrome(executable_path=chromedriver, chrome_options=chrome_options)        # open Chrome browser

        browser.get(url)    

        content = browser.page_source

        print("content: " + str(content))

    finally:

        if browser: browser.quit()

        if display: display.stop()

 

 

if __name__ == '__main__':

    url = 'https://ip.cn'

    url = 'https://mimvp.com/'

    url = 'https://proxy.mimvp.com/ip.php'

 

    # http, https Password Authorization , success

    spider_url_chrome_by_https(url)

 

3、 Running effect , Verify success

content: <html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>140.143.62.84</body></html>

 

 

Selenium + Chrome Diver Using user name and password authentication HTTP Proxy method ( Upgraded version

By default ,Chrome Of --proxy-server="http://ip:port" Parameter does not support setting user name and password authentication .

So that makes "Selenium + Chrome Driver" Can't use HTTP Basic Authentication Of HTTP agent .

An alternative is to use IP Address the authentication , MIPO agent Provide a white list ip to grant authorization , Belong to IP Address the authentication , See MIPO agent  -  Membership Center  -  White list ip

But in the domestic network environment , Most users use ADSL Formal network access ,IP It is changing. (ISP Dynamic switching ), So it's impossible to use IP Address binding Authentication .

therefore , There is an urgent need to find a way to make Chrome automatically HTTP Proxy user name password authentication scheme .

Stackoverflow Someone on the website shared an advantage  Chrome plug-in unit   The scheme of automatic proxy user password authentication is very good ,

Detailed address :how-to-override-basic-authentication-in-selenium2-with-java-using-chrome-driver

MIPO agent R & D engineers of , On the basis of this idea, use Python It's automated Chrome Plug in creation process ,

According to the appointed agent “username:[email protected]:port” It can automatically create a Chrome Proxy plug-in ,

And then you can do it in "Selenium + Chrome Driver" Through the installation of the plug-in, the agent configuration function is realized ,

The specific code is as follows :

1、 Create template folder  Chrome-proxy-helper

As shown in the figure above , Create... In turn :

1) Create template folder  

Chrome-proxy-helper

 

2) establish  background.js

vim Chrome-proxy-helper/background.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

var config = {

    mode: "fixed_servers",

    rules: {

      singleProxy: {

        scheme: "http",

        host: "mimvp_proxy_host",

        port: parseInt(mimvp_proxy_port)

      },

      bypassList: ["mimvp.com"]

    }

  };

 

chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});

 

function callbackFn(details) {

    return {

        authCredentials: {

            username: "mimvp_username",

            password: "mimvp_password"

        }

    };

}

 

chrome.webRequest.onAuthRequired.addListener(

        callbackFn,

        {urls: ["<all_urls>"]},

        ['blocking']

);</all_urls>

 

3) establish  manifest.json

vim Chrome-proxy-helper/manifest.json

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

{

    "version": "1.0.0",

    "manifest_version": 2,

    "name": "Chrome Proxy",

    "permissions": [

        "proxy",

        "tabs",

        "unlimitedStorage",

        "storage",

        "<all_urls>",

        "webRequest",

        "webRequestBlocking"

    ],

    "background": {

        "scripts": ["background.js"]

    },

    "minimum_chrome_version":"22.0.0"

}

 

2、 establish zip Packaged functions

stay python Script , establish zip Packaged functions

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

import os, re, time, zipfile

from selenium import webdriver

 

def get_chrome_proxy_extension(proxy):

    """ Get one Chrome Agent extension , It is configured with a designated agent ( Password authentication with user name )

        proxy - Appointed agent , Format : username:[email protected]:port

    """

     

    # Chrome Reference template for proxy plug-ins https://github.com/RobinDev/Selenium-Chrome-HTTP-Private-Proxy

    CHROME_PROXY_HELPER_DIR = 'Chrome-proxy-helper'     # Custom directory name , Put in the current directory of the agent project

     

    # Store custom Chrome Directory of proxy extension files , Generally, it is the current directory at the same level

    # Generated zip Path is :chrome-proxy-extensions/[email protected]_19480.zip

    CUSTOM_CHROME_PROXY_EXTENSIONS_DIR = 'chrome-proxy-extensions' 

 

    m = re.compile('([^:]+):([^\@]+)\@([\d\.]+):(\d+)').search(proxy)

    if m:

        # Extract the parameters of the agent

        username = m.groups()[0]

        password = m.groups()[1]

        ip = m.groups()[2]

        port = m.groups()[3]

        # Create a custom Chrome Agent extension (zip file )

        if not os.path.exists(CUSTOM_CHROME_PROXY_EXTENSIONS_DIR):

            os.mkdir(CUSTOM_CHROME_PROXY_EXTENSIONS_DIR)

        extension_file_path = os.path.join(CUSTOM_CHROME_PROXY_EXTENSIONS_DIR, '{}.zip'.format(proxy.replace(':', '_')))

         

        # The extension file does not exist , establish

        if not os.path.exists(extension_file_path):

            zf = zipfile.ZipFile(extension_file_path, mode='w')

            zf.write(os.path.join(CHROME_PROXY_HELPER_DIR, 'manifest.json'), 'manifest.json')

            # Replace the proxy parameters in the template

            background_content = open(os.path.join(CHROME_PROXY_HELPER_DIR, 'background.js')).read()

            background_content = background_content.replace('mimvp_proxy_host', ip)

            background_content = background_content.replace('mimvp_proxy_port', port)

            background_content = background_content.replace('mimvp_username', username)

            background_content = background_content.replace('mimvp_password', password)

            zf.writestr('background.js', background_content)

            zf.close()

        return extension_file_path

    else:

        raise Exception('Invalid proxy format. Should be username:[email protected]:port')

 

3、 To write Python The use of scripts, proxy functions

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

## webdriver + chrome + proxy + https (https Password Authorization , Automatic packaging zip)

## MIPO agent :https://proxy.mimvp.com

def spider_url_chrome_by_https2(url):

    browser = None

    display = None

    try:

        display = Display(visible=0, size=(800, 600))

        display.start()

         

        proxy = 'mimvp-guest:[email protected]:19480'

        chrome_options = Options()

        chrome_options = webdriver.ChromeOptions()

        chrome_options.add_extension(get_chrome_proxy_extension(proxy))

         

        chromedriver = '/usr/local/bin/chromedriver'

        browser = webdriver.Chrome(executable_path=chromedriver, chrome_options=chrome_options)        # open Chrome browser

        browser.get(url)    

        content = browser.page_source

        print("content: " + str(content))

    finally:

        if browser: browser.quit()

        if display: display.stop()

 

 

 

if __name__ == '__main__':

    url = 'https://ip.cn'

    url = 'https://mimvp.com/'

    url = 'https://proxy.mimvp.com/ip.php'

 

    # http, https Password Authorization , success

    spider_url_chrome_by_https2(url)

 

4、 Running results , Verify success

content: <html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>140.143.62.84</body></html>

 

5、 Summary

Through templates , Use scripts to automatically create zip file , The automatic dynamic call proxy is realized , Can be fully flexible use of MIPO agent

 

 

Selenium + chromedriver Proxy usage , I won't support it socks5, It's not successful

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

## webdriver + chrome + proxy + socks (socks Password Authorization )

## MIPO agent :https://proxy.mimvp.com

def spider_url_chrome_by_socks(url):

    browser = None

    display = None

     

    ## White list ip, Please see the MIPO agent member center : https://proxy.mimvp.com/usercenter/userinfo.php?p=whiteip

    mimvp_proxy = {

                    'ip'            : '140.143.62.84',      # ip

                    'port_https'    : 62288,                # http, https

                    'port_socks'    : 62289,                # socks5

                    'username'      : 'mimvp-user',

                    'password'      : 'mimvp-pass'

                  }

     

    try:

        display = Display(visible=0, size=(800, 600))

        display.start()

         

        capabilities = dict(DesiredCapabilities.CHROME)

        capabilities['proxy'] = {

                                    'proxyType'    : 'MANUAL',

#                                     'httpProxy'    : mimvp_proxy['ip'] + ":" + str(mimvp_proxy['port_https']),

#                                     'sslProxy'     : mimvp_proxy['ip'] + ":" + str(mimvp_proxy['port_https']),

                                    'socksProxy'   : mimvp_proxy['ip'] + ":" + str(mimvp_proxy['port_socks']),

                                    'ftpProxy'     : mimvp_proxy['ip'] + ":" + str(mimvp_proxy['port_https']),

                                    'noProxy'      : 'localhost,127.0.0.1',

                                    'class'        : "org.openqa.selenium.Proxy",

                                    'autodetect'   : False

                                }

         

        capabilities['proxy']['socksUsername'] = mimvp_proxy['username']

        capabilities['proxy']['socksPassword'] = mimvp_proxy['password']

         

        chromedriver = '/usr/local/bin/chromedriver'

        browser = webdriver.Chrome(chromedriver, desired_capabilities=capabilities)

        browser.get(url)    

        content = browser.page_source

        print("content: " + str(content))

    finally:

        if browser: browser.quit()

        if display: display.stop()

 

 

Complete proxy example , See the example of using the MIPO agent :

https://proxy.mimvp.com/demo2.php  (Selenium Python)

 

More proxy examples , Please see the official of MIPO agent github:

https://github.com/mimvp/mimvp-proxy-demo

 

In this paper , Test agent ip, All from MIPO agent :

https://proxy.mimvp.com

 

 

Additional notes :

Chrome-proxy-helper  There's an official version :

https://github.com/sunboy-2050/Chrome-proxy-helper

Introduction

By default, Chrome use the system proxy setting (IE proxy settings on Windows platform ), but sometime we want to set proxy ONLY for chrome, not the whole system.

Chrome proxy helper extension use Chrome native proxy API to set proxy, support socks5, socks4, http and https protocol and pac script, Fast And Simple.

Features

  • support socks4, socks5, http, https proxy settings
  • support pac proxy settings
  • support bypass list
  • support online pac script
  • support customer proxy rules
  • support proxy authentication
  • support extension settings synchronize

 

版权声明
本文为[Sunshine island Master]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database