python实现不同ip访问网址_Python请求,如何为每个请求绑定到不同的源IP?

I'm trying to learn some python, and i'm having issues with the logic in what I want to test.

Currently my code is written in a way that binding to source_address doesn't change when the process starts

import socket

import requests

real_create_conn = socket.create_connection

def set_src_addr(*args):

address, timeout = args[0], args[1]

source_address = ('201.X.X.1', 0)

return real_create_conn(address, timeout, source_address)

socket.create_connection = set_src_addr

r = requests.get('http://www.mywebpage.com/main')

print r.status_code

if r.status_code == 404

print "Webpage Down!"

r = requests.get('http://www.mywebpage.com/blog')

print r.status_code

if r.status_code == 204

print "Error occured!"

I'm looking to do something like this where

import socket

import requests

While 1:

#bind to source address 201.X.X.1

#Send request to main webpage

#print result

time.sleep(300) # 5 minutes

#bind to source address 201.X.X.12

#Send request to blog webpage

#print result

time.sleep(300) # 5 minutes

解决方案

For each request, there is no elegant solution, but you'll need to use a requests Session object and mount a new transport adapter for each request.

You can find example code for the transport adapter in this issue comment, or you can use the adapter included in the requests-toolbelt package, like so

import requests

from requests_toolbelt.adapters import source

responses = []

s = requests.Session()

for source_ip, url in list_of_sources_and_urls:

new_source = source.SourceAddressAdapter(source_ip)

s.mount('http://', new_source)

s.mount('https://', new_source)

responses.append(s.get(url))

That assumes that list_of_sources_and_urls looks like

[('127.0.0.1', 'https://google.com'),

('255.255.254.0', 'https://yahoo.com'),

# ...

]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值