gpt4 book ai didi

java - 如何通过Selenium点击超链接?

转载 作者:行者123 更新时间:2023-12-01 06:22:53 25 4
gpt4 key购买 nike

我想执行此操作:

1)前往http://www.bbc.co.uk/search?q= (完成)

2)搜索“apple”(完成)

3)点击提交(完成)

4)单击第一个结果或所有结果(这是我用硬代码完成的,如果有任何方法可以选择第一个结果,我们将不胜感激)(正在工作)

<小时/>

我已经完成了前3步。但是,对于第4步,我不知道该怎么做。因为超链接不包含ID

 <h1 itemprop="headline"><a href="http://www.bbc.co.uk/music/artists/12eec8cf-cd35-410d-91e7-31343029ac39">Apple</a></h1>
<p class="summary short">&hellip;The BBC artist page for <em>Apple</em>. Find the best clips, programmes, news and interviews&hellip;</p>
<p class="summary medium">&hellip;The BBC artist page for <em>Apple</em>. Find the best clips, programmes, news and interviews.&hellip;</p>

完整代码:

WebDriver driver;
System.setProperty("webdriver.gecko.driver", "C:\\Users\\Downloads\\geckodriver-v0.10.0-win64\\wires.exe");
driver =new FirefoxDriver();


driver.get("http://www.bbc.co.uk/search?q=");
driver.findElement(By.id("orb-search-q")).sendKeys("apple");//enter apple
driver.findElement(By.id("orb-search-button")).click(); //click submit button

最佳答案

以下任何方法都应该适合您,但 findElements 方法应该更好地满足您的目的

driver.findElement(By.linkText("Apple")) :Assuming there is only one apple, either ways it will click the first "Apple" link
driver.findElement(By.xpath("//a[contains(@href, "music/artists")

or driver.findElements(By.linkText("Apple")).get(0)
// or whatever the index of the first link will be
driver.findElements(By.xpath("//a[contains(@href, "music/artists")).get(0)

关于java - 如何通过Selenium点击超链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39685246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com