Home > Back-end >  Python Selenium Web Driver Pass Integer Variable in Url
Python Selenium Web Driver Pass Integer Variable in Url

Time:04-14

I'm using Python \ Selenium \ Chrome driver to perform webscraping. I want to pass an INT variable (id) to a URL - how do I do this? I have tried all the below but Python errors on this line:

  id = 2000
  
  # Part 1: Customer:
  #urlg = 'https://mythirteen.co.uk/customerRest/show/?id=2000' working but need to pass variable
  #urlg = 'https://mywebsite.com/customerRest/show/?id=' %(id)
  #urlg = 'https://mywebsite.com/customerRest/show/?id={id}' 
  # urlg = 'https://mywebsite.com/customerRest/show/?id='.format(id)
  # urlg = 'https://mywebsite.com/customerRest/show/?id=' id
  # urlg = "https://mywebsite.com/customerRest/show/?id=".format(id)
  # urlg = 'https://mywebsite.com/customerRest/show/?id=' % id
  driver.get(urlg)

I receive errors such as:

TypeError: not all arguments converted during string formatting

I know it its not a string though - id is INT.

Ultimately, I will need to loop through and increase the id 1 each time, but for now I just want to be able pass the actual variable.

CodePudding user response:

If you want to concatenate strings and integer, for most methods you have to cast the integer to a string with str(id).

Otherwise I really like using f-strings:

urlg = f'https://mywebsite.com/customerRest/show/?id={id}'

CodePudding user response:

The problem with the methods you are trying is you essentially aren't telling it where to put the string, or trying to concat a string and an int

so this 'https://mywebsite.com/customerRest/show/?id=' %(id) needs to be 'https://mywebsite.com/customerRest/show/?id=%s' %(id)

So all these would work:

Also, I would not use id as the variable, as it's a reserved function in python. It also could make more sense to make it more descriptive:

customerId = 2000

urlg = 'https://mythirteen.co.uk/customerRest/show/?id=2000' working but need to pass variable
urlg = 'https://mywebsite.com/customerRest/show/?id=%s' %(customerId)
urlg = 'https://mywebsite.com/customerRest/show/?id=%s' %customerId
urlg = f'https://mywebsite.com/customerRest/show/?id={customerId}' 
urlg = 'https://mywebsite.com/customerRest/show/?id={}'.format(customerId)
urlg = 'https://mywebsite.com/customerRest/show/?id=' str(customerId)
  • Related