Выполнять веб-поиск через C # Windows форм - PullRequest
0 голосов
/ 07 марта 2020

Я пытаюсь реализовать поиск в Интернете, чтобы получить заголовки сайтов в поиске Google.
Я получил код, который хорошо работает на других сайтах, но с помощью Google я получил дублированные результаты.

Я пытался и пытался, но я не вижу, в чем ошибка.

Код упрощён:

public partial class Form1 : Form
{
    WebBrowser navegador = new WebBrowser();

    private void Form1_Load(object sender, EventArgs e)
    {
        navegador.ScriptErrorsSuppressed = true;
        navegador.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.datos);
    }

    private void datos(object sender, EventArgs e)
    {
        try
        {
            foreach (HtmlElement etiqueta in navegador.Document.All)
            {
                if (etiqueta.GetAttribute("classname").Contains("LC20lb DKV0Md"))
                {
                    listBox1.Items.Add(etiqueta.InnerText); 
                }
            }
        }
        catch (Exception exception) {  }
    }

    private void function(object sender, EventArgs e)
    {
        /// string query = "https://google.com/search?q=" + query_box.Text;
        navegador.Navigate("https://google.com/search?q=water");
        /// this.Text = query;
    }
}

Результат:

Result

Ответы [ 2 ]

1 голос
/ 07 марта 2020

Я не знаю, как работает Google, но вы можете предотвратить подобные дубликаты

if(!listBox1.Items.Contains(etiqueta.InnerText))
        listBox1.Items.Add(etiqueta.InnerText);
0 голосов
/ 24 марта 2020

После нескольких дней изучения и улучшения кода я решил изменить список для таблицы. Кроме того, теперь запросы не дублируются и располагаются в таблице, как и ожидалось

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;


namespace SourceDownloader
{

    public partial class Form1 : Form
    {
        strs valor = new strs();
        public Form1()
        {
            InitializeComponent();
        }


        WebBrowser navegador = new WebBrowser();
        private void Form1_Load(object sender, EventArgs e)
        {
            navegador.ScriptErrorsSuppressed = true;

            navegador.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.datos);

        }
        private void datos(object sender, EventArgs e)
        {
            try
            {

                foreach (HtmlElement etq in navegador.Document.All)
                {
                    if (etq.GetAttribute("classname").Contains("r")) /// LC20lb DKV0Md
                    {
                        foreach (HtmlElement a_et in etq.GetElementsByTagName("a"))
                        {
                            valor.link = a_et.GetAttribute("href");
                        }
                        foreach (HtmlElement t_et in etq.GetElementsByTagName("h3"))
                        {
                            valor.tit = t_et.InnerText;
                        }
                        bool exist = dataGridView1.Rows.Cast<DataGridViewRow>().Any(row => Convert.ToString(row.Cells["link"].Value) == valor.link);
                        var s1 = valor.link;
                        bool b = s1.Contains("google.com");
                        bool a = s1.Contains("googleusercontent");
                        if (!exist /* && !b && !a*/)
                        {

                            dataGridView1.Rows.Insert(0, valor.tit, valor.link);

                        }
                    }
                    if (etq.GetAttribute("classname").Contains("G0iuSb"))
                    {
                        valor.next = etq.GetAttribute("href");
                    }
                }
                more_ops.Enabled = true;
            }
            catch (Exception)
            {

            }
        }

        private void function(object sender, EventArgs e)
        {
            string query = "https://google.com/search?q=" + query_box.Text;
            navegador.Navigate(query);
            this.Text = query;
        }

        private void more_ops_Click(object sender, EventArgs e)
        {
            string query = valor.next;
            navegador.Navigate(query);
            this.Text = query;

        }

        private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

            try
            {
                var msg = dataGridView1.CurrentCell.Value;
                System.Diagnostics.Process.Start(msg.ToString());
            }
            catch (Exception)
            {
                MessageBox.Show("Error");
            }
        }

        private void Enter(object sender, KeyPressEventArgs e)
        {



            if (e.KeyChar == (char)Keys.Return)
            {
                string texto = query_box.Text;
                texto = texto.Replace("\n", "");
                query_box.Text = texto;

                string query = "https://google.com/search?q=" + query_box.Text;
                navegador.Navigate(query);
                this.Text = query;
            }

        }
    }

    /// global values

    class strs
    {
        private string _link = "N/A";
        private string _tit = "N/A";
        private string _next = "N/A";
        public string tit
        {
            get
            {
                return _tit;
            }
            set
            {
                _tit = value;
            }
        }
        public string link
        {
            get
            {
                return _link;
            }
            set
            {
                _link = value;
            }
        }
        public string next
        {
            get
            {
                return _next;
            }
            set
            {
                _next = value;
            }
        }


    }
}

...