Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

how to get attribute value using selenium and css

I have the following HTML code:

<a href="/search/?p=2&q=move&mt=1"> 2 </a>

I would like to get what is contained in href, ie, I was looking for a command which would give me "/search/?p=2&q=move&mt=1" value for href.

Could someone please help me with the respective command and css locator in selenium, for the above query?

if I have something like:

<a href="/search/?p=2&q=move&mt=1"> 2 </a> 
<a href="/search/?p=2&q=move&mt=2"> 3 </a> 

Out of these two if I was to get the attribute value for href whose text conatins '2', then how would my css locator synatx look like?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your HTML consists solely of that one <a> tag, then this should do it:

String href = selenium.getAttribute("css=a@href");

You use the DefaultSelenium#getAttribute() method and pass in a CSS locator, an @ symbol, and the name of the attribute you want to fetch. In this case, you select the a and get its @href.

In response to your comment/edit:

  1. The part after @ tells Selenium that that part is the name of the attribute.

  2. You should place :contains('2') before @href because it's part of the locator, not the attribute. So, like this:

    selenium.getAttribute("css=a:contains('2')@href");
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...