代理服务的介绍:
代理的设置:
① urllib的代理设置
1 from urllib.error import URLError
2 from urllib.request import ProxyHandler, build_opener
3
4 proxy = '127.0.0.1:8888'
5 #需要认证的代理
6 #proxy = 'username:[email protected]:8888'
7
8 #使用ProxyHandler设置代理
9 proxy_handler = ProxyHandler({
10 'http': 'http://' + proxy,
11 'https': 'https://' + proxy
12 })
13 #传入参数创建Opener对象
14 opener = build_opener(proxy_handler)
15 try:
16 response = opener.open('http://httpbin.org/get')
17 print(response.read().decode('utf-8'))
18 except URLError as e:
19 print(e.reason)
② requests的代理设置
1 import requests
2
3 proxy = '127.0.0.1:8888'
4 #需要认证的代理
5 #proxy = 'username:[email protected]:8888'
6
7 proxies = {
8 'http': 'http://' + proxy,
9 'https': 'https://' + proxy,
10 }
11 try:
12 response = requests.get('http://httpbin.org/get', proxies=proxies)
13 print(response.text)
14 except requests.exceptions.ConnectionError as e:
15 print('Error', e.args)
③ Selenium的代理使用
1 from selenium import webdriver
2
3 service_args = [
4 '--proxy=127.0.0.1:9743',
5 '--proxy-type=http',
6 #'--proxy-auth=username:password' #带认证代理
7 ]
8
9 browser = webdriver.PhantomJS(service_args=service_args)
10 browser.get('http://httpbin.org/get')
11 print(browser.page_source)
1 from selenium import webdriver
2
3 proxy = '127.0.0.1:9743'
4 chrome_options = webdriver.ChromeOptions()
5 chrome_options.add_argument('--proxy-server=http://' + proxy)
6 chrome = webdriver.Chrome(chrome_options=chrome_options)
7 chrome.get('http://httpbin.org/get')
④ 在Scrapy使用代理
1 #在Scrapy的Downloader Middleware中间件里
2 ...
3 def process_request(self, request, spider):
4 request.meta['proxy'] = 'http://127.0.0.1:9743'
5 ...
免费代理IP的使用
我们可以从互联网中获取免费的代理IP:如:西刺
1 import requests,random
2
3 #定义代理池
4 proxy_list = [
5 '182.39.6.245:38634',
6 '115.210.181.31:34301',
7 '123.161.152.38:23201',
8 '222.85.5.187:26675',
9 '123.161.152.31:23127',
10 ]
11
12 # 随机选择一个代理
13 proxy = random.choice(proxy_list)
14
15 proxies = {
16 'http': 'http://' + proxy,
17 'https': 'https://' + proxy,
18 }
19 try:
20 response = requests.get('http://httpbin.org/get', proxies=proxies)
21 print(response.text)
22 except requests.exceptions.ConnectionError as e:
23 print('Error', e.args)
24
收费代理IP的使用
收费代理还是很多的如:
在requests中使用收费代理
1 import requests
2
3 # 从代理服务中获取一个代理IP
4 proxy = requests.get("http://tvp.daxiangdaili.com/ip/?tid=559775358931681&num=1").text
5 proxies = {
6 'http': 'http://' + proxy,
7 'https': 'https://' + proxy,
8 }
9 try:
10 response = requests.get('http://httpbin.org/get', proxies=proxies)
11 print(response.text)
12 except requests.exceptions.ConnectionError as e:
13 print('Error', e.args)