0

Building a scraper with selenium in python. Trying to select a number of buttons in sequence that have sequential titles of the form 'Race n' where n is an integer.

I want to be able to do something like:

driver.find_element_by_css_selector("a[title*=race_i]").click()

where the variable race_i = 'Race ' + str(i)

Is it possible to feed the css or xpath lookup a variable, rather than a plain string? The number of buttons varies so I need this function to be adaptable and work for any value of n.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Welcome to SO. You can append the variable as follows. `driver.find_element_by_css_selector("a[title*=Race" + str(i) + "]").click()` – supputuri Mar 17 '19 at 20:35

3 Answers3

0

How about you just concat the variable to the xpath/css selector?

driver.find_element_by_css_selector("a[title*=" + race_i + "]").click()
Ayoub_B
  • 702
  • 7
  • 19
0

Use format function such as

for i in range(1,10):
 driver.find_element_by_css_selector("a[title*=race_{}]".format(i)).click()
KunduK
  • 32,888
  • 5
  • 17
  • 41
0

To find an element through the variable title you can use either of the following Locator Strategies:

  • css_selector:

    for i in range(1,5):
        driver.find_element_by_css_selector("a[title*='race_'"+ str(i) +"]").click()
    
  • xpath:

    for i in range(1,5):
        driver.find_element_by_xpath('//a[contains(@title, "race_{}")]'.format(i)).click()
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352