Victor
Victor

Reputation: 77

how to use Selenium to click something

I have two simple questions relevant to Selenium. Actually I am new to this framework.

The questions are raised for:

<a href="http://url.com" onclick="somejsfunc();" title="title_text">HERE ARE CHINESE CHARACTERS</a>

and

<a href="javascript:void(0);" onclick="anotherjsfunc();">HERE ARE ANOTHER CHINESE CHARACTERS</a>

How can I use selenium to click each anchor?

Please note that the first has the keyword "title", I know I may use it for match, but no idea how to realize it. I don't plan to use the CHARACTERS presented there, because it varies depending on different projects.

And the second, in this case, the CHINESE CHARACTERS are fixed. Due to there is no other clue, I think I will have to only use it for detection and issue a click event by Selenium.

Please advise, thanks.

Upvotes: 1

Views: 1051

Answers (2)

alecxe
alecxe

Reputation: 474191

You have multiple ways to find both links. Which option to choose depends on the locations of the links on the page, uniqueness of element attributes, text etc.

That said, there are two relevant methods that should be tried first:

Here is how you should use them:

first_link = driver.find_element_by_link_text(u'HERE ARE CHINESE CHARACTERS')
first_link.click()

second_link = driver.find_element_by_link_text(u'HERE ARE ANOTHER CHINESE CHARACTERS')
second_link.click()

where driver is a Webdriver instance, e.g.:

from selenium import webdriver

driver = webdriver.Firefox()

If you cannot rely on the link texts, then check title and onclick attributes and use one of the following methods:

Example (using the first method of two):

first_link = driver.find_element_by_xpath('//a[@title="title_text"]')
first_link.click()

second_link = driver.find_element_by_xpath('//a[@onclick="anotherjsfunc();"]')
second_link.click()

Upvotes: 5

Saifur
Saifur

Reputation: 16201

You can use cssSelector in both cases. css for first a tag should look like

[title='title_text']

and 2nd a tag

[onclick='anotherjsfunc();']

Upvotes: 1

Related Questions