VS2015 C# コマンドラインアプリ作成について教えてください。


以下のURLを参照してclassの値を撮ろうとしています。
http://www.atmarkit.co.jp/fdotnet/dotnettips/908classname/classname.html
http://www.atmarkit.co.jp/fdotnet/dotnettips/687nondispbrowser/nondispbrowser.html

例として取得しようとしているものは以下のurl
http://ejje.weblio.jp/content/solid

class=phoneticEjjeDesc>sάlɪd</span><span class=phoneticEjjeDc>(米国英語)</span>, <span

上記の米国英語のsάlɪdです。

ソースは以下のように書き換えました。
static void Main() {

     省略


foreach (HtmlElement e in doc.GetElementsByTagName("className")) {

string c = e.GetAttribute("className");
string text = e.InnerText;
if (!string.IsNullOrEmpty(c)
&& !string.IsNullOrEmpty(text)) {
text = text.Replace("\r\n", ""); // 改行文字の削除
Console.WriteLine(c);
Console.WriteLine(text);
}
}
}

取れませんでした。デバックするとclassNameでは1つも対象がありませんでした。classにしても同じでした。registoryでwebbrowerのバージョンを11に指定しても同じでした。
実行環境はwindows 10です。

回答の条件
  • 1人1回まで
  • 登録:
  • 終了:2017/04/07 13:55:38
※ 有料アンケート・ポイント付き質問機能は2023年2月28日に終了しました。

ベストアンサー

id:a-kuma3 No.1

回答回数4974ベストアンサー獲得回数2154

ポイント200pt

ここ、違います。SPAN タグを対象にします。

//  foreach (HtmlElement e in doc.GetElementsByTagName("className")) {
    foreach (HtmlElement e in doc.GetElementsByTagName("SPAN")) {

対象を選ぶところも違います。
Null 判定だけじゃなくて、e.GetAttribute("className") で取得した値が "phoneticEjjeDesc" かどうかの判定も必要です。

id:mai_mai_mail

早速返信ありがとうございます。
教えていただいたように書きましたが、取得できませんでした。どこが悪いかご教授いただけますか?

foreach (HtmlElement e in doc.GetElementsByTagName("class")) {
foreach (HtmlElement e2 in doc.GetElementsByTagName("SPAN")) {
string c = e.GetAttribute("class");
string text = e.InnerText;
if (!string.IsNullOrEmpty(c) && !string.IsNullOrEmpty(text) ) {
if (c == "phoneticEjjeDesc") {
text = text.Replace("\r\n", ""); // 改行文字の削除
Console.WriteLine(c);
Console.WriteLine(text);
}
}
}
}

2017/04/06 13:09:51
id:a-kuma3

こんな感じになるかなと。

foreach (HtmlElement e in doc.GetElementsByTagName("SPAN")) {
    string c = e.GetAttribute("className");
    string text = e.InnerText;
    if (!string.IsNullOrEmpty(c) && !string.IsNullOrEmpty(text) ) {
        if (c == "phoneticEjjeDesc") {
            text = text.Replace("\r\n", ""); // 改行文字の削除
            Console.WriteLine(c);
            Console.WriteLine(text);
        }
    }
}

doc.GetElementsByTagName("class") のループを無くして、クラス属性の取得を className にしました。

少なくとも、ループの内側に入るはずです。
クラス属性は "className" で取れると思います。

2017/04/06 13:20:15

コメントはまだありません

この質問への反応(ブックマークコメント)

「あの人に答えてほしい」「この質問はあの人が答えられそう」というときに、回答リクエストを送ってみてましょう。

これ以上回答リクエストを送信することはできません。制限について

回答リクエストを送信したユーザーはいません