【问题标题】:Fetching html element from src using webrequest and substring + indexof使用 webrequest 和 substring + indexof 从 src 获取 html 元素
【发布时间】:2019-10-04 13:52:42
【问题描述】:

你好溢出社区,

我有一个小问题。我写了一个类,它只是一个简单的获取请求,其中包含 url、引用者和 cookie 的参数,然后它返回 pagesrc,这是我的获取字符串函数的消息,它有一个消息、开始和停止参数。

这是类:

class HttpMethods
{
    public static string Fetch(string url, string referer, ref CookieContainer cookies)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.CookieContainer = cookies;
        request.UserAgent = "" ;
        request.Referer = referer;

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        cookies.Add(response.Cookies);


        string pageSrc;
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            pageSrc = sr.ReadToEnd();
        }

        return pageSrc;
    }

}

这是我的主要功能:

    static void Main(string[] args)
    {

        CookieContainer myCookies = new CookieContainer();
        string myStr = HttpMethods.Fetch("localhost", "localhost", ref myCookies);
        void fetchStr (string message , string start, string stop)
        {
            int startIndex = message.IndexOf(start) + start.Length;
            int stopIndex = message.IndexOf(stop);
            Console.Write( message.Substring(startIndex, stopIndex - startIndex) );
        }

        fetchStr(myStr, "I am a String ", " to fetch");
        Console.ReadKey();

    }
}

当我只获取纯文本时一切正常,但是当我想获取一个元素时,它返回给我长度不能小于 0,这是未找到某些字符串时的响应。

这真的很奇怪,这里有一个例子:

            //Original Sentence : I am a string please fetch me dude.
        fetchStr(myStr, "I am a ", " fetch me dude");

这将返回:请字符串

但是当我尝试获取这部分时:

            //Original Sentence : name="_playerToken" value="a8276964-fdac-4d63-ae25-5752f157a21b" />
        fetchStr(myStr, "name=\"_playerToken\" value=\"", "\"/>");

这将返回长度不能小于0。

这是我的 Visual Studio 输出的屏幕截图:

Visual Studio Value Output

有人知道问题出在哪里吗?

【问题讨论】:

  • 请注意:request.CookieContainer = cookies; 足以处理 cookie;不需要cookies.Add(response.Cookies);。

标签: c# substring httpwebrequest indexof


【解决方案1】:

完全改变我的原始答案,因为刚刚注意到您正试图从整个 html 输出中获取 />,因此返回它看到的第一个实例,而不是 _playerToken 键之后的那个。

我建议将您的 fetchStr 方法改为正则表达式查询。

String regex = "name=\"_playerToken\" value=\"([^\"]*)\"";
var match = Regex.Matches(message, regex);
if (match.Count > 0)
{
    string result = match[0].Groups[1].Value;
}

【讨论】:

  • System.ArgumentOutOfRangeException: "Die Länge darf nicht kleiner als 0 (null) sein. Parametername: length" :( 但 stopIndex 现在是 11705
  • regex 需要哪些 using 语句?我从未使用过它,我的 vstudio 出现错误
  • System.Text.RegularExpressions 如果你复制我答案中的代码你会得到预期的结果,我自己也试过了
  • 该死的你是我的英雄兄弟!你能解释一下吗:“([^\”]*)\“”好吗?
  • 不用担心它基本上会在 value=" 之后得到任何字符串,这不是 " 直到它遇到另一个 "。如果它解决了你的问题,请标记我的答案并更正:)
猜你喜欢
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多