Changing The Ip Address For Urllib2
I am trying to change the IP address from which my simple python code connects to my website. import urllib.request as urllib2 # change of IP address page = urllib2.urlopen('http:
Solution 1:
Try using the following code:
import urllib.request as urllib2
proxy = urllib2.ProxyHandler({"http": "118.69.140.108:53281"})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
page = urllib2.urlopen("http://example.com/")
Alternatively you can use the requests
library which makes it easier:
importrequestsurl="http://example.com/"
page = requests.get(url, proxies={"http":"118.69.140.108:53281"})
hope this helps
Solution 2:
This is a simple example without error handling, reconnecting. I hope I wrote the correct answer ;)
import urllib.request as urllib2
http_proxy = {
'user': ''
, 'passwd': ''
, 'server': '67.205.151.211'
, 'port': '3128'
}
# change of IP address
page = urllib2.urlopen("http://httpbin.org/ip").read()
print(page)
# http://username:password@someproxyserver.com:1337
http_proxy_full_auth_string = "http://%s:%s@%s:%s" % (http_proxy["user"],
http_proxy["passwd"],
http_proxy["server"],
http_proxy["port"])
proxy_handler = urllib2.ProxyHandler({"http": http_proxy_full_auth_string,
"https": http_proxy_full_auth_string})
opener = urllib2.build_opener(proxy_handler)
postDatas = {"User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
"Cache-Control": "no-cache",
"Pragma": "no-cache"}
request = urllib2.Request("http://httpbin.org/ip", None, postDatas)
connection = opener.open(request, timeout=10)
page = connection.read()
# except Exception as err:# # Si il y a une erreur de connexion (timeout etc.)# result.add_error(err, "%s ne repond pas" % url)# else:
connection.close()
print(page)
Post a Comment for "Changing The Ip Address For Urllib2"