Roman
Roman

Reputation: 3941

Python selenium find element by certain innerHTML and then a parent and child

Currently I am trying to find a certain element on the website which can be identified by its inner html. After I find this item I need to find its parent and a child.

Here is the example, I need to populate the textarea with different content, the only way I can find the correct textarea is finding the needed td which can be identified by its innerHTML

<tr>
  <td class="alignRight"> 1 </td>
  <textarea></textarea>
</tr>
<tr>
  <td class="alignRight"> 2 </td>
  <textarea></textarea>
</tr>
<tr>
  <td class="alignRight"> 3 </td>
  <textarea></textarea>
</tr>
<tr>
  <td class="alignRight"> 4 </td>
  <textarea></textarea>
</tr>

I have tryed a few solutions but so far no results, the closest I got is this:

elem = driver.find_element_by_css_selector('td.alignRight').get_attribute('innerHTML')
print (elem, type(elem))

The problem here is it finds only the first element. The best thing would be if I could directly find the element WHERE innterHTML = Value

Upvotes: 0

Views: 1194

Answers (2)

Andersson
Andersson

Reputation: 52665

Try to use below code to get required texarea by preceding sibling td with specific value:

value = "1"
driver.find_element_by_xpath("//td[.='%s']/following-sibling::textarea" % value)

Upvotes: 2

Amol Chavan
Amol Chavan

Reputation: 3970

I am not familar with python but I can explain the logic:-

  1. Create dynamic Xpath to find out sibling node of required node using value[1,2,3], where you can send value as parameter.
  2. Find out parent node using xpath.
  3. Find the child are using tagname

I tried writing code, syntax may be incorrect.

value="what ever value you want to provide[1,2,]"
requiredXpath=".//td[@class='alignRight' and text()="+value+"]"
elem = driver.find_element_by_xpath(requiredXpath).find_element_by_xpath("..").find_element_by_tag_name("textarea)

Upvotes: 0

Related Questions