使用python替换url中的端口
发布时间:2020-12-20 11:48:50 所属栏目:Python 来源:网络整理
导读:我想更改给定网址中的端口. OLD = http://test:7000/vcc3 NEW = http://test:7777/vcc3 我尝试下面的代码,我能够更改URL但无法更改端口. from urlparse import urlparse aaa = urlparse('http://test:7000/vcc3') aaa.hostnametest aaa.port7000aaa._replace
我想更改给定网址中的端口.
OLD = http://test:7000/vcc3 我尝试下面的代码,我能够更改URL但无法更改端口. >>> from urlparse import urlparse >>> aaa = urlparse('http://test:7000/vcc3') >>> aaa.hostname test >>> aaa.port 7000 >>>aaa._replace(netloc=aaa.netloc.replace(aaa.hostname,"newurl")).geturl() 'http://newurl:7000/vcc3' >>>aaa._replace(netloc=aaa.netloc.replace(aaa.port,"7777")).geturl() Traceback (most recent call last): File "<stdin>",line 1,in <module> TypeError: expected a character buffer object 解决方法
这不是一个特别好的错误信息.它抱怨,因为你将ParseResult.port(一个int)传递给字符串的replace方法,它需要一个str.只需将端口字符串化,然后再将其传入:
aaa._replace(netloc=aaa.netloc.replace(str(aaa.port),"7777")) 我很惊讶没有一种使用urlparse库设置端口的简单方法.这感觉就像一个疏忽.理想情况下,你可以说像parseresult._replace(port = 7777),但唉,that doesn’t work. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |