如何使用 Selenium 获取页面上第一条新闻的 header 信息

How to get the header info of the first news on the page using Selenium

我正在尝试导航到每个链接并在 page.but 上获取他们的第一条新闻 无法为所有页面的 header 信息获取唯一的 xpath

参考附图,它显示了 2 个元素。我怎样才能让它变得独一无二,只获取 header / title 新闻。

可以select只使用父元素的第一个子元素,然后指向子元素,例如:

//div/div[1]/div/a/h3[@class="gs-c-promo-heading__title gel-paragon-bold nw-o-link-split__text"]

[1] 等于 :first-child

该页面上有很多 headers,并且它们正在更改。我的意思是有些新闻即将发布并从此页面中删除。
如果您想获取所有新闻标题文本,您可以获取所有 headers 元素,然后遍历它们并提取它们的文本。
像这样:

List<WebElement> headers = driver.findElements(By.xpath("//h3[@class='gs-c-promo-heading__title gel-pica-bold nw-o-link-split__text']"));
for (WebElement header : headers){    
    ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", header);
    System.out.println(header.getText());
}

要检索第一条新闻的header需要归纳WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • JavaxpathgetText():

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(@class, 'gs-u-display-inline-block@m')]//h3[@class='gs-c-promo-heading__title gel-paragon-bold nw-o-link-split__text']"))).getText());
    
  • Pythoncss_selectortext属性:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div[class*='gs-u-display-inline-block@m'] h3.gs-c-promo-heading__title.gel-paragon-bold.nw-o-link-split__text"))).text)
    
  • 控制台输出:

    Russia orders oldest rights group Memorial to shut
    
  • 注意:对于Python客户,您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC