代理的设置

做测试之前,我们需要先获取一个可用代理,这里我用 Fiddler 来设置代理:https://www.cnblogs.com/pzk7788/p/10605300.html

urllib 如何使用代理:

from urllib.error import URLError
from urllib.request import ProxyHandler, build_opener

proxy = '127.0.0.1:8888'
proxy_handler = ProxyHandler({
    'http': 'http://' + proxy,
    'https': 'https://' + proxy
})
opener = build_opener(proxy_handler)

try:
    response = opener.open('http://httpbin.org/get')
    print(response.read().decode('utf-8'))
except URLError as e:
    print(e.reason)

request 如何使用代理:

import requests

proxy = '127.0.0.1:8888'
proxies = {
    'http': 'http://' + proxy,
    'https': 'https://' + proxy
}

try:
    response = requests.get('http://httpbin.org/get', proxies=proxies)
    print(response.text)
except requests.exceptions.ConnectionError as e:
    print('Error', e.args)

Selenium 如何使用代理:

from selenium import webdriver

proxy = '127.0.0.1:8888'
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=http://' + proxy)
browser = webdriver.Chrome(chrome_options=chrome_options)
browser.get('http://httpbin.org/get')

 

 

 

 

 

   

posted @ 2019-04-02 11:14  孔雀东南飞  阅读(433)  评论(0编辑  收藏  举报