我喜歡接近這些任務以試圖找到一個通用的解決方案,使其ç適用於(希望)任何情況/查詢。爲了做到這一點,我們需要查看結果頁面的HTML並找到搜索結果的容器,以便我們縮小個別搜索結果的範圍並找到每個結果的鏈接。然後我們可以根據一些標準選擇我們想要的任何結果,然後按照該鏈接等。
如果您查看結果頁面的HTML,搜索結果將全部包含在此元素中。
<ol class="search-results results" start="1" data-total-results="16514">
和像
<li data-result-number="1">
<li data-result-number="2">
<li data-result-number="3">
<li data-result-number="4">
例如由孩子,這裏是整個第一結果
<li data-result-number="1">
<article class=" media-text" itemscope="">
<aside class="flags top"></aside>
<aside class="flags mid"></aside>
<div>
<h1 itemprop="headline">
<a href="http://www.bbc.co.uk/music/artists/12eec8cf-cd35-410d-91e7-31343029ac39">Apple</a>
</h1>
<p class="summary short">…The BBC artist page for <em>Apple</em>. Find the best clips, programmes, news and interviews…</p>
<p class="summary medium">…The BBC artist page for <em>Apple</em>. Find the best clips, programmes, news and interviews.…</p>
<p class="summary long">…The BBC artist page for <em>Apple</em>. Find the best clips, programmes, news and interviews.…</p>
<footer>
<dl>
<dt>Tags</dt>
<dd><span class="signpost-site" data-site="music">Music</span><span class="signpost-section">Artists</span>
</dd>
</dl>
</footer>
</div>
<a href="http://www.bbc.co.uk/music/artists/12eec8cf-cd35-410d-91e7-31343029ac39" class="rs_touch"></a>
<span class="divide"></span>
</article>
</li>
由此我們可以看到,標題,蘋果,處於h1
標籤,幷包含我們尋求的A
。有了這個信息,我們可以製作一個CSS選擇器,如ol.search-results > li h1 > a
,它會在標題內找到結果A
標記。現在我們有了這個,我們可以編寫如下所示的代碼,爲每個搜索結果轉儲標題。
String searchTerm = "apple";
driver.get("http://www.bbc.co.uk/search?q=" + searchTerm);
List<WebElement> headingLinks = driver.findElements(By.cssSelector("ol.search-results > li h1 > a"));
for (WebElement headingLink : headingLinks)
{
System.out.println(headingLink.getText());
}
,如果你想點擊第一個鏈接,轉儲以下
Apple
Apple of my Eye
Down on the Farm: Series 1: Farm Park and Apple Crisps
Cinnamon, apple and custard Danish
Apple, sultana and cinnamon swirls
The logic in Apple buying McLaren
Supercar maker McLaren denies Apple investment report
Scotch egg with apple
Cider and apple cake
Simon Mayo Drivetime: Blackberry and Apple Bake
在這一點上,你只需要更改代碼以
String searchTerm = "apple";
driver.get("http://www.bbc.co.uk/search?q=" + searchTerm);
List<WebElement> headingLinks = driver.findElements(By.cssSelector("ol.search-results > li h1 > a"));
headingLinks.get(0).click();
第二個鏈接會be
headingLinks.get(1).click();
... an d等等......
在一般情況下,如果沒有任何鏈接完全是搜索詞,例如「蘋果」?這不起作用。 – JeffC
然後他們可以使用By.partialLinkText方法。這個概念仍然保持不變。 – Sid
如果使用參數化的搜索字符串作爲文本,效果會更好 – Sid