代理的設置

作測試以前,咱們須要先獲取一個可用代理,這裏我用 Fiddler 來設置代理:http://www.javashuo.com/article/p-wmifkjna-da.htmlhtml

urllib 如何使用代理:web

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 如何使用代理:chrome

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')
相關文章
相關標籤/搜索