Get part of a Selenium Python url


I have this URL and I just want to get a part of it:

The part I want to obtain is the id: 1024374 to then enter it in this other url:

I explain a little to clear up doubts. With selenium I am redirected to the first URL. Here I want to get the ID of the url. I thought I would do it with driver.current_url but I get the whole url. Then I need the ID that I get to enter the second url where the ID goes.

Working with Python 2.7

asked by Martin Bouhier 24.10.2017 в 02:25

2 answers


You have several options, from using str.split to regular expressions, or you can use the module urlparse next to str.rpartition :

import urlparse

url = ''
url_parts = urlparse.urlparse(url,  allow_fragments = False)
id = url_parts[2].rpartition('/')[2]

In Python 3 the module is urllib.parse .

If your urls always have the same structure you can simply use str.rpartition twice:

url = ''
id = url.rpartition('/')[2].rpartition('?')[0] 

str.rpartition divides a string using the last occurrence of the separator provided as an argument. Return a tuple with three elements where the second is the separator, the first what is left and the third what is on your right.


To get the URL as a string you only need to use the current_url attribute:

url = driver.current_url

To create your new url format the string:

base = "{}&at=MOBILE_WEB&_sid=60c7302b-9ede-4308-93f6-014975706aff"
new_url = base.format(id)
answered by 24.10.2017 / 02:52

I add the method of regular expressions although in your case, since it is about urls, the best solution is FJSevilla.

import re

url = ""
m ='(^.*\/)([0-9]{7})(\?.*$)', url)


As you will see, the second group is the id you are looking for. The explanation is:

(^         # Primer grupo, desde el comienzo
.*         # Cualquier caracter
\/)        # Hasta la primer barra antes del segundo grupo
([0-9]{7}) # 2do grupo solo 7 números, puedes hacer también {1,7} de 1 a 7 números
(\?        # 3er grupo desde el ?
.*         # Cualquier caracter
$)         # Hasta el final de la cadena
answered by 24.10.2017 в 03:13