1

The following is the HTML structure:

<div class='list'>
  <div>
    <p class='code'>12345</p>
    <p class='name'>abc</p>
  </div>
  <div>
    <p class='code'>23456</p>
    <p class='name'>bcd</p>
  </div>
</div>

And there is a config.py for user input. If the user input 23456 to config.code, how can the selenium python select the second object? I am using find_by_css_selector() to locate and select the object, but it can only select the first object, which is Code='12345'. I tried to use find_by_link_text(), but it is a <p> element not <a> element. Anyone can help.....

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Yuk Chan
  • 137
  • 2
  • 9

2 Answers2

1

Try the below xpath:

code = '23456'
element = driver.find_element_by_xpath("//p[@class='code' and text()='" +code +"']")
frianH
  • 7,295
  • 6
  • 20
  • 45
  • 1
    Right. Then to get the sibling I think it would be driver.find_element_by_xpath("//p[@class='code' and text()='" +code +"']/following-sibling::p") – Logan George Jun 04 '20 at 07:43
  • @frianH it wokrs! But i am not really understand the use of xpath. Can you explain more on "//p[@class='code' and text()='" +code +"']" ? – Yuk Chan Jun 04 '20 at 07:45
  • @LoganGeorge what's the meaning of sibling u are talking? – Yuk Chan Jun 04 '20 at 07:46
  • @YukChan that's just simple logic using the `AND` expression. Trying search for a `p` tag with the class name is `code` and the tag has the text `23456`. – frianH Jun 04 '20 at 08:10
  • @frianH then how about '" +code +"'? not really understand this syntax – Yuk Chan Jun 04 '20 at 08:36
  • 1
    @YukChan it's for string merger. – frianH Jun 04 '20 at 08:40
1

To locate the element with respect to the input by the user using Selenium and you need to to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using variable in XPATH:

    user_input = '23456'
    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='list']//div/p[@class='code' and text()='" +user_input+ "']")))
    
  • Using %s in XPATH:

    user_input = '23456'
    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='list']//div/p[@class='code' and text()='%s']"% str(user_input))))
    
  • Using format() in XPATH:

    user_input = '23456'
    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='list']//div/p[@class='code' and text()='{}']".format(str(user_input)))))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352