'Xpath using using random.randint(2,8) always identifies the first item using Python Selenium
Working on a random question picker from a codechef webpage but the problem is even when i am using random value of i, it always clicks the first question.
Code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time
import random
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://www.codechef.com/practice?page=0&limit=20&sort_by=difficulty_rating& sort_order=asc&search=&start_rating=0&end_rating=999&topic=&tags=&group=all")
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
time.sleep(3)
# element = driver.find_element_by_link_text("Roller Coaster")
i = random.randint(2,8)
try:
item = WebDriverWait(driver, 25).until(
EC.presence_of_element_located((By.XPATH, "/html/body/div/div/div/div/div[3]/div/div[2]/div/div[3]/div/div/table/tbody/tr['+str(i)+']/td[2]/div/a"))
)
item.click()
except:
driver.quit()
Solution 1:[1]
You need to make two simple tweaks as follows:
To click() on the clickable element instead of presence_of_element_located() you need to induce WebDriverWait for the element_to_be_clickable().
You need to replace the single quotes i.e.
'+str(i)+'with double quotes"+str(i)+"Your effective code block will be:
driver.get("https://www.codechef.com/practice?page=0&limit=20&sort_by=difficulty_rating&sort_order=asc&search=&start_rating=0&end_rating=999&topic=&tags=&group=all") WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#gdpr-i-love-cookies"))).click() i = random.randint(2,8) print(i) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div/div/div/div/div[3]/div/div[2]/div/div[3]/div/div/table/tbody/tr["+str(i)+"]/td[2]/div/a"))).click()Console Output:
7
Solution 2:[2]
Just change the Xpath to the following f-String and it will work perfectly:
Change this: "/html/body/div/div/div/div/div[3]/div/div[2]/div/div[3]/div/div/table/tbody/tr['+str(i)+']/td[2]/div/a"
To this: f"/html/body/div/div/div/div/div[3]/div/div[2]/div/div[3]/div/div/table/tbody/tr[{i}]/td[2]/div/a"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | undetected Selenium |
| Solution 2 |
