0

我想从网站中提取一些信息,并使用HtmlAgilityPacklinq在 HTML 上创建查询。

在此特定示例中,我想获取 A 标记中 href 属性中 m_name 的值,然后获取 IMG 标记中 src 属性的值。

<A href="/index.php?lang=eng&ssid=&wbid=&refid=website.com&mref=&showall=0&Submit=m_info&refname=&id=37447&m_name=LacosteShoe">
    <DIV name="prdiv1" id="prdiv1" overflow:hidden;">
        <IMG name="pic1" id="pic1" class=pic_2 alt="for sale here for 2 days" title="for sale here for 2 days" src="item/preview/37447_pr2.jpg?55995" >
    </DIV>
</A>

我想制作List<string,string>这些值中的一个,以便在此示例中

list.add("LacosteShoe","item/preview/37447_pr2.jpg?55995");

是否可以在 linq 查询中执行此操作?对于我的初学者知识来说,这还很遥远。此外,如果属性 href 不存在,我还必须确保它不会失败。

到目前为止,我基本上得到了这个:

var query = document.DocumentNode.Descendants("a")
   .Where(a => a.Attributes["href"].Value.Contains("m_name=")
Select();
4

2 回答 2

2
var query = document.DocumentNode.Descendants("a")
    .Where(a => a.Attributes["href"].Value.Contains("m_name=")
    .Select(b => new {Name=ExtractName(b.Attributes["href"].Value),
    Link=b.Descendants("div").First()
    .Descendants("img").First().Attributes["src"].Value}).ToList();

定义ExtractName(string str);从 href 值中提取名称的函数。您可以为此使用正则表达式。

于 2013-09-15T14:09:24.890 回答
1

尝试

List<string> products = document.DocumentNode.Descendants("a")
.Where(a => a.Attributes["href"] != null   
 &&a.Attributes["href"].Value.Contains("m_name=")).Select(l => 
l.Attributes["href"].Substring(l.Attributes["href"].IndexOf("m_name=") + 7)).ToList();
于 2013-09-15T14:07:36.293 回答