【问题标题】:Getting attribute of element in XPath获取 XPath 中元素的属性
【发布时间】:2017-07-28 06:37:49
【问题描述】:

我想学习网络抓取。因此,我开始练习。我正在尝试使用XPathHTML 获取数据广告ID。

HTML 结构如下:

<body id="z1234">
    <div class="viewport">
        <div class="g-row">
            <div class="g-col-9">
                <div class="cBox cBox--content cBox--resultList">
                    <div class="cBox-body cBox-body--resultitem dealerAd rbt-reg rbt-no-top"><a class="link--muted no--text--decoration result-item" href="url" data-ad-id="248059713"></a>
                </div>
            </div>
        </div>
    </div>
</body>

&lt;a class="link--muted no--text--decoration result item" &gt; 的 XPath 是 //*[@id="z1234"]/div[3]/div[4]/div[2]/div[1]/div[11]/a。如果我选择不同的车,只有最后一个 div 会改变。

据此我写C#代码:

var url = "https://suchen.mobile.de/fahrzeuge/search.html?damageUnrepaired=NO_DAMAGE_UNREPAIRED&isSearchRequest=true&maxPowerAsArray=KW&maxPrice=10000&minPowerAsArray=KW&minPrice=10000&scopeId=C";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string sourceCode = sr.ReadToEnd();

            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(sourceCode);




            var rows = document.DocumentNode.SelectNodes("//*[@id='z1234']/div[3]/div[4]/div[2]/div[1]/div[11]");


            foreach (var row in rows)
            {
                var id = row.SelectSingleNode("a[@data-ad-id]").InnerText;
                Console.WriteLine("id:" + id);
            }
        }

我无法从此节点获得任何东西。它是空的。如何获取 data-ad-id?

编辑 我更改了我的 C# 代码:

var rows = document.DocumentNode.SelectNodes("//a[@data-ad-id]")[0];
var id = rows.Attributes["data-ad-id"].Value;

现在我可以得到data-ad-id.

【问题讨论】:

    标签: html xpath html-agility-pack


    【解决方案1】:

    根据网站的代码,我可以感觉到您没有该“A”标签的内部文本。它只包含 DIV 和 IMG 标签。

    您需要使用

    获取 data-ad-id
    //a[@data-ad-id]/@data-ad-id
    

    【讨论】:

    • 感谢您的快速回复!我试过这个,但是,我得到car name 而不是data-ad-id。 @Ganesh Pandhere
    • 我不确定 C# 代码是如何编写的。但是我已经给出了代码来获取我们通常按照我提到的方式执行的属性值。
    • 我希望它对你有用@heyaa 否则我试图找到与 SelectSingleNode 相关的东西以供参考stackoverflow.com/questions/3004587/…
    • 当我开始尝试时,[@id="z1234"]/div[3]/div[4]/div[2]/div[1]/div[11]/a 只有最后一个 div(对于这种情况:div[11])在 XPath 中发生了变化。 div 一个一个地增加。但是现在,它依次增加。我怎样才能得到每个 i 在 div[i] 。 @Ganesh Pandhere
    猜你喜欢
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 2020-04-22
    • 1970-01-01
    • 2021-08-04
    相关资源
    最近更新 更多