Mary
Mary

Reputation: 797

**Cannot** using the following code via selenium to click <i class="E"></i> with href="#"

Cannot using the following code via selenium to click

<a href="#" class="C" rel="D" style="display: block;"><i class="E"></i></a> no hyperlink in href tag <a href="#"></a> no text <i class="E"></i> so that cannot be click

*i save the HTML code into tmpfile.org, it just last an hours, so the URL may be expired

Python Code

from selenium import webdriver
driver.get("https://tmpfiles.org/dl/65768/button_2021.html")
driver.find_element_by_xpath("//href[@class="E"]//a").click()

HTML code

html = """<html><body><div class="A">
  <div class="B">
    <a href="#" class="C" rel="D" style="display: block;">
      <i class="E"></i>
    </a>
  </div>
<div class="B">
<span class="J" id="I">H</span>
  </div>
  <div class="B">
    <a href="#" class="F" rel="" style="display: none;">
  <i class="G"></i>
</a>
</div>
&nbsp;
<div id="B" class="B"><div>
<a href="http://www.google.com" class="pno">K</a>
</div> <div>
<a href="http://www.google.com" class="pno">L</a>
</div> <div>
</div></body></html>"""

Upvotes: 0

Views: 78

Answers (3)

Mary
Mary

Reputation: 797

first list out all elements with following code:

a = driver.find_elements_by_class_name('B')
c = []
for x in a:
    c.append(x.text)
print(c)

and we can see some result in the elements, which mean we may do sth on it

Execution Result

['']
['', 'H']
['', 'H', '']
['', 'H', '', 'K\nL']

and then using the following code to click

driver.find_elements_by_class_name('B')[0]

Upvotes: 0

cruisepandey
cruisepandey

Reputation: 29362

two things :

find_elements 

returns a list so you can not use click on it. since click is just for single web element.

this xpath //href[@class="E"]//a is wrong since href is not a tag.

Instead do this :

driver.find_element_by_xpath("//i[@class='E']/..").click()

but it should not redirect you anywhere since href has # which will not redirect you nowhere.

Update 1 :

In case you want to click on 'K', you can use below code :

wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "K"))).click()

Imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Upvotes: 1

itronic1990
itronic1990

Reputation: 1441

See if this works, I assume you are trying to click on a tag above <i class='E'>

driver.find_element_by_xpath("//i[@class='E']//ancestor::a[@class='C']").click()

Upvotes: 1

Related Questions