0

The first xpath in below can find what I want in most cases, but in some cases the xpath is slightly different, which makes it harder to solve the problem.

first xpath in most cases -->

driver.find_element_by_xpath('/html/body/div[2]/div[2]/div/ul/div/li[3]/ul/li[4]/div/a').click()

second xpath in some cases-->

driver.find_element_by_xpath('/html/body/div[2]/div[2]/div/ul/div/li[5]/ul/li[4]/div/a').click()

So I'm searching the another way to find the xpath by the specific text.

another way-->

driver.get(url)
html_source = driver.page_source
 if "the specific text" in html_source:
   <<find xpath where the specific text is>>

<div ext:tree-node-id="7" class="x-tree-node-el x-tree-node-leaf x-unselectable text" unselectable="on"><span class="x-tree-node-indent"><img alt="" src="/js/extjs/resources/images/default/s.gif" class="x-tree-elbow-line"></span><img alt="" src="/js/extjs/resources/images/default/s.gif" class="x-tree-ec-icon x-tree-elbow"><img alt="" src="/js/extjs/resources/images/default/s.gif" class="x-tree-node-icon" unselectable="on"><a hidefocus="on" class="x-tree-node-anchor" href="#" tabindex="1"><span unselectable="on">the specific text</span></a></div>

Is it possible or is there another way?

  • your xpath's and the html is not in sync, share the relevant html. and It seems very generic, please be specific. Please read [mcve] and edit your post accordingly and follow same in all future posts – Dev Sep 03 '20 at 14:16

1 Answers1

0

Option 1: Directly use classname and get the text or press

driver.find_element_by_class_name("my-class").click()
driver.find_element_by_class_name("my-class").text

Option 2: Don't start with /html/body/bla/bla/bla you can call anchor tag with specific classname and get the text or press

press_me = driver.find_element_by_xpath("//a[@class='my-class']").click()
get_me_text = driver.find_element_by_xpath("//a[@class='my-class']").text

I hope its clear :)

Salman Waheed
  • 190
  • 3
  • 6