我喜欢接近这些任务以试图找到一个通用的解决方案,使其ç适用于(希望)任何情况/查询。为了做到这一点,我们需要查看结果页面的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