Replace port in url using python

murali koripally

I want to change the port in given url.

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

I tried below code code, I am able to change the URL but not able to change the port.

>>> 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
Benjamin Hodgson

It's not a particularly good error message. It's complaining because you're passing ParseResult.port, an int, to the string's replace method which expects a str. Just stringify port before you pass it in:

aaa._replace(netloc=aaa.netloc.replace(str(aaa.port), "7777"))

I'm astonished that there isn't a simple way to set the port using the urlparse library. It feels like an oversight. Ideally you'd be able to say something like parseresult._replace(port=7777), but alas, that doesn't work.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Replace .php in URL with / using .htaccess

From Dev

Replace .php in URL with / using .htaccess

From Dev

Replace text in a url using PHP

From Dev

search and replace using python

From Dev

Getting port from URL string using Javascript

From Dev

How Do I Replace The Tomcat Port Using Maven-Cargo?

From Dev

How to make a serial port sniffer sniffing physical port using a python

From Dev

Replace a word using IIS URL Rewrite

From Dev

How to replace entire URL using Regex?

From Dev

How to replace query parameter in URL using Regex?

From Dev

Replace the page from a url using php

From Dev

replace strings in url using regular expression

From Dev

Dynamically replace part in URL using Regex

From Dev

Replace a word using IIS URL Rewrite

From Dev

How to replace query parameter in URL using Regex?

From Dev

Replace URL in PHP code using HTTP Class

From Dev

Using search and replace on URL query string

From Dev

Python replace, using patterns in array

From Dev

Replace words in a text using python

From Dev

Using python replace function in for loop

From Dev

Issue using replace function in python

From Dev

Python subprocess rsync using sshpass and specify port

From Dev

Reading from RS 232 port using python

From Dev

Delay from serial port using Python

From Dev

Delay from serial port using Python

From Dev

Port code from python to java using OpenCV

From Dev

How to remove url variable, then replace with new url using jQuery

From Dev

Android: Create a URL using Uri.Builder().build() with port numbers

From Dev

How to get the port number from the URL using jQuery?