InvalidSelectorError:不允许使用复合类名

时间:2015-02-14 18:05:19

标签: java selenium xpath selenium-webdriver web-scraping

我正在尝试使用

获取以下每个元素
element = driver.findElement(By.className("code-list-item code-list-item-public "));

inspect元素的输出如下。

<div class="column one-fourth codesearch-aside"></div>

<div class="column three-fourths codesearch-results">

    <div class="sort-bar"></div>
    <div id="code_search_results">
        <div class="code-list">
            <div class="code-list-item code-list-item-public "></div>
            <div class="code-list-item code-list-item-public "></div>
            <div class="code-list-item code-list-item-public "></div>
            <div class="code-list-item code-list-item-public "></div>
            <div class="code-list-item code-list-item-public "></div>
            <div class="code-list-item code-list-item-public "></div>
            <div class="code-list-item code-list-item-public "></div>
            <div class="code-list-item code-list-item-public "></div>
            <div class="code-list-item code-list-item-public "></div>
            <div class="code-list-item code-list-item-public "></div>
        </div>

但是它失败并抛出以下错误。

Caused by: org.openqa.selenium.InvalidSelectorException: The given selector code-list-item code-list-item-public  is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: Compound class names not permitted
For documentation on this error, please visit: http://seleniumhq.org/exceptions/invalid_selector_exception.html

另外,我如何遍历每个类?其中每一个都包含子部分,我希望在移动到下一部分之前进一步单独处理。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

如果我不必,我不会担心课程名称。我会使用css选择器。

.code-list>div

css注意.表示类,所以我指向带有code-list>div类的div,它允许我们选择所有子div

您还可以使用:nth-child()函数来获取索引号为

的特定子div

.code-list>div:nth-child(1)

上面的css允许你选择第一个子div

根据你的截图

.code-list>div:nth-child(1)>a

可帮助OP了解应如何处理此方案的代码块

//maximizing the window for better view
driver.manage().window().maximize();

//a selector to find all the links on the page
By selector = By.xpath("//p[@class='title']/a[1]");

//finding the list of all elements
List<WebElement> list = driver.findElements(selector);

/*Iterating over the collection may throw StaleElementReference exception due to DOM refresh
according to my knowledge for loop is best in such case
*/
for (int i = 0; i<list.size(); i++){

    new WebDriverWait(driver,10).until(ExpectedConditions.elementToBeClickable(selector));

    //Click on the title
    driver.findElements(selector).get(i).click();

    //Navigating back to the main page. This is not feasible but no other option present due to page structure
    driver.navigate().back();
}