【问题标题】:HtmlUnit - Unable to get anchors from divHtmlUnit - 无法从 div 获取锚点
【发布时间】:2014-04-14 14:58:18
【问题描述】:

我要定位的 HTML 页面的 divs 如下所示:

<div class="white-row1">
  <div class="results">
    <div class="profile">
      <a href="hrefThatIWant.com" class>
        <img src = "http://imgsource.jpg" border="0" width="150" height="150 alt>
      </a>
    </div>
   </div>
</div>
<div class="white-row2">
// same content as the div above
</div>

我想废弃收集列表中每个 div 中的 href。

这是我当前的代码:

List<HtmlAnchor> profileDivLinks = (List)htmlPage.getByXPath("//div[@class='profile']//@href"); 
for(HtmlAnchor link:profileDivLinks)
{
    System.out.println(link.getHrefAttribute());
}

这是我收到的错误(出现在 for 语句的第一行):

Exception in thread "main" java.lang.ClassCastException: com.gargoylesoftware.htmlunit.html.DomAttr cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlAnchor 

你认为问题是什么?

【问题讨论】:

    标签: html xpath web-scraping href htmlunit


    【解决方案1】:

    问题是您正在获取一个属性,然后将该属性转换为锚点。我想对您的代码进行最小更改的解决方案就是修改 XPath 以返回一个锚点:

    htmlPage.getByXPath("//div[@class='profile']//a"); 
    

    【讨论】:

    • 谢谢!这是有道理的。
    【解决方案2】:

    试试

    //div[@class='profile']//data(@href)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      相关资源
      最近更新 更多