【问题标题】:How can I get specific links in a class?如何获得课程中的特定链接?
【发布时间】:2014-06-28 03:56:23
【问题描述】:

我有一个这样的html结构:

<div class="YazarDetayTarih_Conteiner">
    <div class="YazarDetayTarih FL">30.Mart.2013, Cumartesi</div>
    <div class="YazarDetayBaslik FL">
<a class="haberlink"  href="http://www.hurriyet.com.tr/yazarlar/22928436.asp">Böyle özür olmaz Serdar Ortaç</a>
       </div>
     </div>
<div class="YazarDetayTarih_Conteiner">
<div class="YazarDetayTarih_Conteiner">

有几个 div class="YazarDetayTarih_Conteiner"> 。我想获得这些href链接。目前当我像

HtmlElementCollection col = web.Document.GetElementsByTagName("a");
foreach (HtmlElement el in col)
{
       link = el.GetAttribute("href");
}

它在页面上提供了所有的 href 链接。我怎样才能只取属于 \a class="haberlink"

的 href

编辑:我无法让它工作。在我尝试richTextBox1.Text += el.GetAttribute("class") 之后它给出了空白页。

在使用节点时,我们可以像 SelectNodes("//*[contains(@class,'haberlink')]");有什么办法吗?

【问题讨论】:

  • 先获取类,检查是否匹配。
  • @MattBurland 如果它会检查所有条目会不会太慢?我需要检查哪个值? if(el.getAttribute("class")=="haberlink") ?
  • 搜索此集合没有不涉及查看集合成员的快捷方式。如果您知道(或只想要)一个结果,您可以在找到匹配项时通过breaking 缩短循环。

标签: c# html


【解决方案1】:

在你的 foreach 循环中,跳过没有所需类的那些:

if(el.GetAttribute("class") != "haberlink")
   continue;

【讨论】:

  • 谢谢。但是当我尝试时仍然无法获取链接 if(el.GetAttribute("class") != "haberlink") continue; richTextBox1.Text += el.GetAttribute("href");
  • 我想我解决了这个问题。它应该是“类名”
猜你喜欢
  • 2013-06-13
  • 2017-08-24
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 2020-04-16
相关资源
最近更新 更多