更改urllib2的IP地址

时间:2019-05-03 17:29:15

标签: python urllib2

我正在尝试更改简单的python代码从其连接到我的网站的IP地址。

#Start out on the branch with the code we want
git checkout branch_a

#create tmp branch same as branch_a (so that we don't change our local branch_a state during the operation)
git branch tmp

#working directory has all the code that we want, on tmp branch
git checkout tmp

# Change the branch head to the branch we want to be on. All the delta
# between the current source code and branch_b is now staged for commit
git rebase --soft branch_b

# Move away from tmp, so our commit will go directly to branch_b
git checkout branch_b

# Now you can examine the proposed commit
git status

# Add the delta we want to the branch
git commit

# Sanity check that the branches have the same content now (should return an empty line)
git diff branch_A..branch_b

# Remove tmp, we don't need it anymore
git branch -D tmp

是否有一个可以轻松启用它的python库?这样,连接到该站点的用户将显示不同的位置。

例如,我要使用IP地址:118.69.140.108和端口53281从该站点抓取本地新闻。

该怎么做,哪个库将启用它?

2 个答案:

答案 0 :(得分:3)

尝试使用以下代码:

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/")

或者,您可以使用requests库,这使它更容易:

import requests

url = "http://example.com/"
page = requests.get(url, proxies={"http":"118.69.140.108:53281"})

希望这会有所帮助

答案 1 :(得分:1)

这是一个简单的示例,没有错误处理,无需重新连接。我希望我写了正确的答案;)

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)