Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace port in url using python

Tags:

python

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
like image 891
murali koripally Avatar asked Jan 27 '16 10:01

murali koripally


People also ask

How do you change the URL in Python?

The replace_urls() method in Python replaces all the URLs in a given text with the replacement string.

Which function from Urllib parse is used to construct a full absolute URL by combining a base URL base with another URL URL?

Use the urljoin method from the urllib. parse module to join a base URL with another URLs, e.g. result = urljoin(base_url, path) . The urljoin method constructs a full (absolute) URL by combining a base URL with another URL.

What is Urlparse in Python?

urlparse()This function parses a URL into six components, returning a 6-tuple. This corresponds to the general structure of a URL. Each tuple item is a string. The components are not broken up in smaller parts (for example, the network location is a single string), and % escapes are not expanded.

What is Netloc in Python?

netloc : Contains the network location - which includes the domain itself (and subdomain if present), the port number, along with an optional credentials in form of username:password . Together it may take form of username:[email protected]:80 .


2 Answers

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.

like image 83
Benjamin Hodgson Avatar answered Sep 28 '22 01:09

Benjamin Hodgson


The details of the port are stored in netloc, so you can simply do:

>>> a = urlparse('http://test:7000/vcc3')
>>> a._replace(netloc='newurl:7777').geturl()
'http://newurl:7777/vcc3'
>>> a._replace(netloc=a.hostname+':7777').geturl()  # Keep the same host
'http://test:7777/vcc3'
like image 39
AChampion Avatar answered Sep 28 '22 02:09

AChampion