使用python替换url中的端口

我想更改给定网址中的端口.

OLD = http://test:7000/vcc3
NEW = http://test:7777/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.

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...