使用python替换url中的端口

使用python替换url中的端口,第1张

概述我想更改给定网址中的端口. OLD = http://test:7000/vcc3 NEW = http://test:7777/vcc3 我尝试下面的代码,我能够更改URL但无法更改端口. >>> from urlparse import urlparse>>> aaa = urlparse('http://test:7000/vcc3')>>> aaa.hostnametest>>> 我想更改给定网址中的端口.

olD = http://test:7000/vcc3
NEW = http://test:7777/vcc3

我尝试下面的代码,我能够更改URL但无法更改端口.

>>> from urlparse import urlparse>>> aaa = urlparse('http://test:7000/vcc3')>>> aaa.hostnametest>>> aaa.port7000>>>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),但唉,@L_301_2@.

总结

以上是内存溢出为你收集整理的使用python替换url中的端口全部内容,希望文章能够帮你解决使用python替换url中的端口所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1193512.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存