【问题标题】:How to select <a> tag HtmlAgilityPack如何选择 <a> 标签 HtmlAgilityPack
【发布时间】:2021-09-26 11:57:44
【问题描述】:

这是我尝试选择的屏幕截图,我从控制台复制了 Xpath,但是当我运行程序时,它指出它是 null:Anchor tag

我尝试将 Xpath 复制到标签以及它上面的标签,它们都返回一个空值,但是当我在浏览器中运行查询并检查页面时,它们都有一个值。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;

namespace AccessID2
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    #region UI Event Handlers
    private void cmdGo_Click(object sender, EventArgs e)
    {
        RestClient rClient = new RestClient();
        rClient.endPoint = txtUrl.Text;

        debugOutput("Searching for Product");

        string strResponse = string.Empty;

        strResponse = rClient.makeRequest();
        debugOutput(strResponse);

        var html = strResponse;

        var htmlDoc = new HtmlAgilityPack.HtmlDocument();
        htmlDoc.LoadHtml(html);

        var htmlNodes = htmlDoc.DocumentNode.SelectNodes("//*[@id='anch_114']");

        txtID.Text = htmlNodes.ToString();
    }

    #endregion

    private void debugOutput(string strDebugText)
    {
        try
        {
            System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
            txtResponse.Text = txtResponse.Text + strDebugText + Environment.NewLine;
            txtResponse.SelectionStart = txtResponse.TextLength;
            txtResponse.ScrollToCaret();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
        }
    }

   

    private void label3_Click(object sender, EventArgs e)
    {

    }
}
}

【问题讨论】:

    标签: c# html parsing


    【解决方案1】:

    只需选择锚元素:

    var htmlNodes = htmlDoc.DocumentNode.SelectNodes("//a[@id='anch_114']");
    

    【讨论】:

    • 谢谢你,不幸的是,它仍然给一个空
    • hmm,这行代码是否返回了你需要的锚点? var anchors = htmlDoc.DocumentNode.Descendants("a").ToList();
    • 我试过这样,它仍然显示为空。这是怎么用的? var htmlDoc = new HtmlAgilityPack.HtmlDocument(); htmlDoc.LoadHtml(html); var idNumber = htmlDoc.DocumentNode.SelectNodes("//a[@id='anch_114']"); var anchors = htmlDoc.DocumentNode.Descendants("a").ToList(); if (idNumber == null) { txtID.Text = "Null Field"; } else { txtID.Text = anchors.ToString(); }
    • 代码看起来不错,但htmlDoc.DocumentNode.Descendants 只是另一种查找某些元素的方法。它返回一个带有锚元素的列表。如果这也返回 null,则可能是加载的 html 有问题。
    • 现在我将 HTML 复制到一个文件中,并将路径设置为变量以从文件中读取它,但它仍然给出 null。我认为您是正确的,但我不确定如何阅读它。
    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 2012-07-06
    相关资源
    最近更新 更多