python 使用IP代理进行http 请求

  • 1
  • 3,708 次浏览
  • A+
所属分类:Python

直接来看个简单的小例子吧:

# -*- coding=utf-8 -*-
#__author__:Mr丶zhang
import urllib2
import requests
from lxml import etree
  
proxy={'http':'120.76.79.21:80'}
test_url="http://ip.filefab.com/index.php"   #ip网站测试 http://ip.filefab.com/index.php
  
resp=urllib2.urlopen(test_url).read()
response = etree.HTML(resp)
ip_addr = response.xpath('//div/h1[@id="ipd"]/span/text()')
print "Before switching the IP address:",ip_addr
#使用代理IP地址之前的访问IP地址
  
try:
    response = requests.get(test_url,proxies = proxy)
    response = etree.HTML(resp)
    ip_addr = response.xpath('//div/h1[@id="ipd"]/span/text()')
    print "Now the IP ADDRESS IS:",ip_addr
    #使用代理IP地址之后的访问IP地址
except Exception:
    print "The IP Address is Useless" #代理IP不可用

IP代理的效果如图所示:

python 使用IP代理进行http 请求

从上图可以看出来,IP地址已经更换,使用IP代理池的原理差不多,灵活运用一下就好了!

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

目前评论:1   其中:访客  0   博主  0

    • avatar 少华 2

      可以结合IP代理池