使用requests庫
class SourcePortAdapter(HTTPAdapter): """"Transport adapter" that allows us to set the source port.""" def __init__(self, port, *args, **kwargs): self.poolmanager = None self._source_port = port super().__init__(*args, **kwargs) def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs): self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, source_address=('', self._source_port)) s = requests.Session() s.mount('https://baidu.com', SourcePortAdapter(54321)) s.get('https://baidu.com')
我用wireshark測試發(fā)現(xiàn)是走的54321端口。
使用pycurl庫
c = pycurl.Curl() c.setopt(c.URL, 'https://curl.haxx.se/dev/') c.setopt(c.LOCALPORT, 54321) c.setopt(c.LOCALPORTRANGE, [52314,56321,5532]) c.perform() c.close()
測試OK,可以直接在curl命令行中測試。
curl --local-port 12520 http://baidu.com
參考
https://stackoverflow.com/questions/47202790/python-requests-how-to-specify-port-for-outgoing-traffic?rq=1
以上這篇Python使用指定端口進(jìn)行http請(qǐng)求的例子就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
