0

Set-up:

I'm using Python + Selenium to do some work.

I have a table with the following html,

<tbody>
    <tr bgcolor="white" class="TRNORM TRCOLHEADER">...</tr>
    <tr bgcolor="white" class="TRNORM cROW">...</tr>
    <tr bgcolor="white" class="TRNORM cROW">...</tr>
    <tr bgcolor="white" class="TRNORM">...</tr>
    <tr bgcolor="white" class="TRNORM">...</tr> 
</tbody>

and I loop over the rows using the following code,

table = browser.find_element_by_css_selector('#formWrapper > tbody > tr:nth-child(3) > td > table > tbody')
for row in table.find_elements_by_xpath('tr'):
    # code for row follows

Issue

I need to loop over class="TRNORM cROW" only.

How do I do this?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
LucSpan
  • 1,831
  • 6
  • 31
  • 66

2 Answers2

0

Use following xpath which will select rows only contains class="TRNORM cROW"

for row in table.find_elements_by_xpath('.//tr[@class="TRNORM cROW"]'):

Or following css selector which will select rows only contains class="TRNORM cROW"

for row in table.find_elements_by_css_selector("tr[class='TRNORM cROW']"):
KunduK
  • 32,888
  • 5
  • 17
  • 41
0

To loop over the elements only with class="TRNORM cROW" you can use either of the following Locator Strategies:

  • Using css_selector:

    for row in browser.find_elements_by_css_selector("#formWrapper > tbody > tr:nth-child(3) > td > table > tbody tr.TRNORM.cROW"):
      # code for row follows
    
  • Using xpath:

    for row in browser.find_elements_by_xpath("//td/table/tbody//tr[@class='TRNORM cROW']"):
      # code for row follows
    

Ideally, you have to induce WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    for row in WebDriverWait(browser, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "#formWrapper > tbody > tr:nth-child(3) > td > table > tbody tr.TRNORM.cROW"))) :
      # code for row follows
    
  • Using XPATH:

    for row in WebDriverWait(browser, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//td/table/tbody//tr[@class='TRNORM cROW']"))):
      # code for row follows
    
  • 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
    # code for row follows
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352