对于低于 HTML 的 Selenium,合适的 Xpath 位置是什么?

What could the appropriate Xpath location for Selenium for below HTML?

大家好 _ 我需要帮助找出正确的 Xpath 位置以从下面提取所有链接 HTML。我尝试了很多组合,包括很多 Google 帮助,但没有解决方案。 HTML 如下所示 -

<div id="fullwidth" class="destLists">
<h1 class="specials" style="padding:0 0 0 30px; background: transparent url(http://q-ec.bstatic.com/static/img/icons/destination_24/48b021a6cd8fa7532053cf41b4cf7a1dce15458a.png) no-repeat 2px 2px;">Destinations</h1>
<div class="description deslast">
<p class="firstpar" style="margin-bottom: 1.2em">
<ul class="destLinks">
<a name="accomodations"/>
<h3>
<table class="general" width="100%" cellspacing="0">
<div class="toTop">
<a name="landmarks"/>
<h3>
<table class="general" width="100%" cellspacing="0">
<div class="toTop">
<a name="districts"/>
<h3>
<table class="general" width="100%" cellspacing="0">
<div class="toTop">
<a name="hotels"/>
<h3>
<table class="general" width="100%" cellspacing="0">
<tbody>
<tr>
<tr>
<td width="50%">
<a href="/hotel/in/clarks-shiraz.en-us.html?sid=94c48c83993c829d5d7f07ba57314600;dcid=4">Hotel Clarks Shiraz</a>
<br/>
<a href="/hotel/in/courtyard-by-marriott-agra.en-us.html?sid=94c48c83993c829d5d7f07ba57314600;dcid=4">Courtyard by Marriott Agra</a>

我想提取所有以 - /hotel/ 开头或包含 - hotel 的 href 链接。下面是我有的,但它不起作用。

List<WebElement> hotelElements = driver.findElementsByXPath("//*[@id='fullwidth' and contains(href, 'hotel')]/div/*/tbody/*/*/a");

可以使用CSS选择器吗?我知道您特别要求使用 XPath,但我通常尽量避免使用 XPath,除非绝对必要(99% 的情况下不需要),因为它们比 CSS 选择器更容易出错、更脆弱且更慢。

试试这个

List<WebElement> links = driver.findElements(By.cssSelector("a[href*='hotel']"));
for (WebElement link : links)
{
    System.out.println(link.getAttribute("href"));
}

它获取 href 包含 (*=) 'hotel' 的所有 A 个标签。该循环只是将找到的每个元素的 href 转储到控制台。你可以在那里做任何你想做的事。

如果您想将以“/hotel/”(^=) 开头的 href 与包含 'hotel' (*=) 的 href 分开,则还有其他变体。看到这个 CSS Selector reference.


编辑 1

既然您已经将此标记为答案...Andrew 刚刚提供了您需要的 XPath,但他的代码需要一些调整。您可以将他的 .findElements() 行与我的其余代码一起使用,它应该可以工作。

试试这个

List<WebElement> links = driver.findElementsByXPath(".//a[contains(href, 'hotel')]");
for (WebElement link : links)
{
    System.out.println(link.getAttribute("href"));
}

您可以通过以下方式找到页面上的所有链接:

".//a[@href]"

你的情况:

List<WebElement> hotelElements = driver.findElementsByXPath(".//a[contains(href, 'hotel')]");

如果您需要从这些链接元素中获取 href,代码将类似于:

List<string> hrefs = new List<string>();
foreach (var link in hotelElements )
{
    hrefs.Add (link.getAttribute("href"));
}