Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# XPath从节点内的多个标记检索值_C#_Html_Xpath_Html Agility Pack - Fatal编程技术网

C# XPath从节点内的多个标记检索值

C# XPath从节点内的多个标记检索值,c#,html,xpath,html-agility-pack,C#,Html,Xpath,Html Agility Pack,我目前正在创建一个爬虫程序,我需要将数据抽象到一个集合中,这样我就可以将它作为一行发送到数据库中,既美观又整洁 这是我的程序的一个剪贴画,它正确地转到目前为止的每个页面,并检索正确的对应url int tempflag = 0; //linkValueList is full of sub urls previously crawled in the program foreach (string str in linkValueList) { string tempURL = base

我目前正在创建一个爬虫程序,我需要将数据抽象到一个集合中,这样我就可以将它作为一行发送到数据库中,既美观又整洁

这是我的程序的一个剪贴画,它正确地转到目前为止的每个页面,并检索正确的对应url

int tempflag = 0;
//linkValueList is full of sub urls previously crawled in the program
foreach (string str in linkValueList)
{
    string tempURL = baseURL + str;
    HtmlWeb tempWeb = new HtmlWeb();
    HtmlDocument tempHtml = tempWeb.Load(tempURL);
    foreach (HtmlNode node in tempHtml.DocumentNode.SelectNodes("//article[@itemprop='product']"))
    {
        //get the category from the linkNameList
        string tempCategory = linkNameList.ElementAt(tempflag);
        //grab url
        string tempHref = node.GetAttributeValue("data-itemurl", string.Empty);
       //grab image url
       //grab brand
       //grab name
       //grab price
       //send to database via INSERT
    }
    tempflag++;
}
这是我正在使用的站点代码,这是一个项目的示例,每个项目看起来都很相似

<article .... itemprop="product" data-itemurl="Item's url">
    <figure>
        <a ....>
            <img .... src="item's image source" ...>
        </a>
        <div ...>
            <a>....</a>
        </div>
    </figure>
    <div ...>
        <a ....>
                <div class="brand" itemprop="brand>Item's Brand</div>
            <div class="title" itemprop="name">Item's Name</div>
        </a>
        <div ....>
            <div class="msrp"></div>
            <div class="price" itemprop="price">$18.99 - $119.99</div>
            <span ...> ... </span>
        </div>
    </div>
</article>

....

确实可以使用
节点子体(“img”)
节点子体(“div”)。其中(d=>d.Attributes.Contains(“itemprop”)和&d.Attributes[“itemprop”].Value.Equals(“price”)


希望有帮助。

确保可以使用另一个XPath在给定元素中进行查询。需要注意的一点是,很多人都遇到过这样的问题,千万不要用
/
来启动相对XPath,因为它会搜索整个文档,如果需要的话,可以用
/
来启动,例如(
SelectSingleNode()
假定始终在此处找到目标元素,否则需要首先检查结果是否为非
null
):


很好,我自己也尝试了好几天,我很接近,但是没有正确的XPath语法。非常感谢!
foreach (HtmlNode node in tempHtml.DocumentNode.SelectNodes("//article[@itemprop='product']"))
{
    img = node.SelectSingleNode(".//img").GetAttributeValue("src","");
    brand = node.SelectSingleNode(".//div[@itemprop='brand']").InnerText.Trim();
    .....
}