我正在尝试使用Selenium Firefox webdriver找到YouTube视频的链接。现在,我得到一个NoSuchElementException。它正确访问了YouTube页面,但找不到第一个链接的元素。我的目标是能够将第一个视频的网址复制到一个字符串中。
String ytlink = "https://www.youtube.com/results?search_query=" + searchTerm;
driver.get(ytlink);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
By cssSelector = By.cssSelector("#item-section-209606 > li:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > h3:nth-child(1) > a:nth-child(1)");
WebElement element = driver.findElement(cssSelector);
我正在使用Intellij并拥有最新版本的selenium。 Firefox用于通过使用Inspect Element定位CSS Selector - 复制CSS Selector。
我想要检索a href =" / watch?v = WPvGqX-TXP0"并将其存储到String
中答案 0 :(得分:0)
您的搜索结果是否始终返回相同的#item-section-?如果这是一个自动生成的数字,它可能导致NoSuchElementException。
我能够使用以下css选择器点击为YouTube搜索返回的第一个链接:
div > div > div.yt-lockup-content > h3 > a