0

我得到当前页面上的所有链接,然后我寻找我需要的链接,然后我想获得这个链接的锚点(“a”的打开和结束标记之间的文本)。我尝试使用“obj.GetAttribute("innerText")”,但它返回一个空字符串。

WebClient client = new WebClient();
string htmlCode = client.DownloadString("http://mysite1.com");

CQ cq = CQ.Create(htmlCode);
foreach (IDomObject obj in cq.Find("a")){
 string href = obj.GetAttribute("href");
   if (href.IndexOf("mysite2.com") != -1){
      //get the anchor of this link
   }
 }
4

1 回答 1

0

终于解决了。

using CsQuery;

CQ cq = CQ.Create(htmlCode);
foreach (IDomObject obj in cq.Find("a")){
        string linkAnchor = obj.InnerHTML;
}

但是俄语文本存在问题。在某些情况下(并非总是),俄语文本被读取为 unicode 字符代码。例如所有的俄罗斯字符都是这样的“ϵ”。所以我写了一个函数来解码俄罗斯字符中这种俄罗斯字符的表示。

private string DecodeFromUTFCode(string input){
    input = input.Replace("&#", "");
    StringBuilder decodedAnchor = new StringBuilder();
    StringBuilder currentUnicodeNum = new StringBuilder();
    bool isInNumber = false;

    for (int i = 0; i <= input.Length - 1; i++){
        if (Char.IsDigit(input[i])){
            isInNumber = true;
        }else{
            isInNumber = false;
            if (input[i] != ';') decodedAnchor.Append(input[i]);
        }

        if (isInNumber){
            currentUnicodeNum.Append(input[i]);
        }

        if ((input[i] == ';') || (i == input.Length - 1)){
            string decoded = char.ConvertFromUtf32(int.Parse(currentUnicodeNum.ToString()));
            decodedAnchor.Append(decoded);
            currentUnicodeNum.Clear();
        }
    }

    return decodedAnchor.ToString();
}
于 2016-09-14T14:06:49.073 回答