python3.0学习七: 用代理访问网页

'''
备注:本程序是为了使用代理来访问网页

'''

import urllib.request
import random


#一个检测网站的ip地址
url='http://www.whatismyip.com.tw'

#可以添加一个ip列表,用于随机访问ip
iplist=['125.62.14.162:3128','111.243.68.23:8080','113.119.204.173:808']



#新建一个代理
proxy_support=urllib.request.ProxyHandler({'http':random.choice(iplist)})

#创建一个opener
opener=urllib.request.build_opener(proxy_support)
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36')]


urllib.request.install_opener(opener)

response=urllib.request.urlopen(url)

html=response.read().decode('utf8')

print(html)



#运行结果如下:

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="description" content="我的IP查詢"/>
    <meta name="keywords" content="查ip,ip查詢,查我的ip,我的ip位址,我的ip位置,偵測我的ip,查詢我的ip,查看我的ip,顯示我的ip,what is my IP,whatismyip,my IP address,my IP proxy"/>
    <title>我的IP位址查詢</title>
  </head>
  <body>
<h1>IP位址</h1> <h2>113.119.204.149</h2><h1>真實IP</h1> <h2>220.178.4.222</h2>

<script type="text/javascript"> var sc_project=6392240; var sc_invisible=1; var sc_security="65d86b9d"; var scJsHost = (("https:" == document.location.protocol) ? "https://secure." : "http://www."); document.write("<sc"+"ript type='text/javascript' src='" + scJsHost + "statcounter.com/counter/counter.js'></"+"script>"); </script>
<noscript><div class="statcounter"><a title="websitestatistics" href="http://statcounter.com/" target="_blank"><img class="statcounter" src="http://c.statcounter.com/6392240/0/65d86b9d/1/" alt="website statistics"></a></div></noscript>

  </body>
</html>

你可能感兴趣的:(python)