打开一个站点时自动在文本框上添加文本

时间:2013-02-22 14:40:28

标签: c# asp.net web-services

所以,我想把一个信息放在一个文本框中,在更特殊的文本框中,一个网站的CNPJ:

  

http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp

但是我没有......所以,我试过了......我试图将cnpj值放在链接的最后,就像这样:

  

http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp?cnpj=00495835000160

但是,网站没有将值放在文本框中......

如何使用网站上的cnpj值输入(网站上没有数字,只是在链接中...)

而且,在C#中,我试过这个:

using System;
using System.IO;
using System.Net;
using System.Text;

namespace ReceitaFederal
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                WebRequest request = WebRequest.Create("http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp");

                string strPost = "cnpj=00495835000160";

                request.Method = "POST";
                request.ContentLength = strPost.Length;
                request.ContentType = "application/x-www-form-urlencoded";

                StreamWriter writer = new StreamWriter(request.GetRequestStream());
                writer.Write(strPost);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream dataStream = response.GetResponseStream();

                StreamReader reader = new StreamReader(dataStream);

                string responseFromServer = reader.ReadToEnd();

                reader.Close();
                dataStream.Close();
                response.Close();

                Console.WriteLine(responseFromServer);
            }
            catch (Exception exec)
            {
                Console.WriteLine(exec.GetType() + "" + exec.Message);
            }
        }
    }
}

5 个答案:

答案 0 :(得分:2)

解决!!!首先添加此cookie容器:

using System;
using System.Net;

namespace ConsultaCNPJ
{
    public class CookieAwareWebClient : WebClient
    {
        private CookieContainer _mContainer;

        public void SetCookieContainer(CookieContainer container)
        {
            _mContainer = container;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            var webRequest = request as HttpWebRequest;
            if (webRequest != null)
            {
                webRequest.CookieContainer = _mContainer;
                webRequest.KeepAlive = true;
                webRequest.ProtocolVersion = HttpVersion.Version10;
            }
            return request;
        }
    }
}

然后将代码编辑为:

using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsultaCNPJ
{
    public class ConsultaCNPJBroker
    {
        private readonly CookieContainer _cookies = new CookieContainer();
        public String DominioReceitaFederal = "http://www.receita.fazenda.gov.br";
        public String GetDataReceitaFederal = "/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao2.asp";
        public String PostDataReceitaFederal = "/pessoajuridica/cnpj/cnpjreva/valida.asp";
        private String _viewState;

        public Bitmap GetCaptcha()
        {
            const string strViewState = "<input type=hidden id=viewstate name=viewstate value='";
            const string strImagemCaptcha = "<img border='0' id='imgcaptcha' alt='Imagem com os caracteres anti robô' src='";
            String htmlResult;

            using (var wc = new CookieAwareWebClient())
            {
                wc.SetCookieContainer(_cookies);
                wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)";
                wc.Headers[HttpRequestHeader.KeepAlive] = "300";
                htmlResult = wc.DownloadString(DominioReceitaFederal + GetDataReceitaFederal);
            }

            if (htmlResult.Length > 0)
            {
                _viewState = htmlResult;

                int posString = _viewState.IndexOf(strViewState, StringComparison.Ordinal);
                _viewState = _viewState.Substring(posString + strViewState.Length);
                posString = _viewState.IndexOf("'>", StringComparison.Ordinal);
                _viewState = _viewState.Substring(0, posString);

                String urlImagemCaptcha = htmlResult;
                posString = urlImagemCaptcha.IndexOf(strImagemCaptcha, StringComparison.Ordinal);
                urlImagemCaptcha = urlImagemCaptcha.Substring(posString + strImagemCaptcha.Length);
                posString = urlImagemCaptcha.IndexOf("'>", StringComparison.Ordinal);
                urlImagemCaptcha = urlImagemCaptcha.Substring(0, posString);
                urlImagemCaptcha = urlImagemCaptcha.Replace("amp;", "");

                if (urlImagemCaptcha.Length > 0)
                {
                    var wc2 = new CookieAwareWebClient();
                    wc2.SetCookieContainer(_cookies);
                    wc2.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)";
                    wc2.Headers[HttpRequestHeader.KeepAlive] = "300";
                    byte[] data = wc2.DownloadData(DominioReceitaFederal + urlImagemCaptcha);

                    return new Bitmap(
                        new MemoryStream(data));
                }
                return null;
            }
            _viewState = "";
            return null;
        }

        public Stream Consulta(string aCNPJ, string aCaptcha, bool removerEspacosDuplos)
        {
            var request = (HttpWebRequest) WebRequest.Create(DominioReceitaFederal + PostDataReceitaFederal);
            request.ProtocolVersion = HttpVersion.Version10;
            request.CookieContainer = _cookies;
            request.Method = "POST";

            string fviewstate = _viewState;
            fviewstate = Uri.EscapeDataString((fviewstate));

            string postData = "";
            postData = postData + "origem=comprovante&";
            postData = postData + "viewstate=" + fviewstate + "&";
            postData = postData + "cnpj=" + new Regex(@"[^\d]").Replace(aCNPJ, string.Empty) + "&";
            postData = postData + "captcha=" + aCaptcha + "&";
            postData = postData + "captchaAudio=&";
            postData = postData + "submit1=Consultar&";
            postData = postData + "search_type=cnpj";

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();
            return response.GetResponseStream();                
        }
    }
}

那就是它!

特别感谢我的好朋友CunhaW!

<强>用法:

首先创建一个带有PictureBox和TextBox的表单,以及像这样的验证码的代理

private readonly ConsultaCNPJBroker _broker = new ConsultaCNPJBroker();
this.ImgCaptcha = new System.Windows.Forms.PictureBox();
this.TbxCaptcha = new System.Windows.Forms.TextBox();

然后使用类似2步骤的查询,首先获取Captcha,然后使用验证码进行查询

private void UpdateCaptcha()
{
    ImgCaptcha.Image = _broker.GetCaptcha();
    TbxCaptcha.Text = string.Empty;
}

此处需要用户交互来解决验证码并填充文本框,最后

private void BtnExecute_OnClick(object sender, EventArgs e)
{
        var pessoaJuridica = _broker.Consulta(TbxCNPJ.Text, TbxCaptcha.Text, true);
        // here you can see props like pessoaJuridica.CNPJ
}

答案 1 :(得分:1)

也许这有助于你,它还没有工作......但几乎就在那里......

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Windows.Forms;

namespace LeituraWeb
{
    public partial class Form1 : Form
    {

        String viewState;
        public String Dominio_ReceitaFederal = "http://www.receita.fazenda.gov.br/";
        public String GetData_ReceitaFederal = "pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao2.asp";
        public String PostData_ReceitaFederal = "pessoajuridica/cnpj/cnpjreva/valida.asp";

        public Form1()
        {
            InitializeComponent();
        }

        private void btnGo_Click(object sender, EventArgs e)
        {

            int PosString;
            String StrViewState = "<input type=hidden id=viewstate name=viewstate value='";
            String StrImagemCaptcha = "<img border='0' id='imgcaptcha' alt='Imagem com os caracteres anti robô' src='";
            String UrlImagemCaptcha = "";
            String HtmlResult = "";

            using (WebClient wc = new WebClient()){
                wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                HtmlResult = wc.DownloadString(Dominio_ReceitaFederal + GetData_ReceitaFederal);
            }

            if (HtmlResult.Length > 0)
            {
                viewState = HtmlResult;

                // executando um crop do viewstate para utilizar no post
                PosString = viewState.IndexOf(StrViewState);
                viewState = viewState.Substring(PosString + StrViewState.Length);
                PosString = viewState.IndexOf("'>");
                viewState = viewState.Substring(0, PosString);

                //executando um crop na url da imagem 
                UrlImagemCaptcha = HtmlResult;
                PosString = UrlImagemCaptcha.IndexOf(StrImagemCaptcha);
                UrlImagemCaptcha = UrlImagemCaptcha.Substring(PosString + StrImagemCaptcha.Length);
                PosString = UrlImagemCaptcha.IndexOf("'>");
                UrlImagemCaptcha = UrlImagemCaptcha.Substring(0, PosString);
                UrlImagemCaptcha = UrlImagemCaptcha.Replace("amp;", "");                

                // populando a imagem do captcha dentro de um picturebox
                if (UrlImagemCaptcha.Length > 0)
                    pictureBox1.Image = new System.Drawing.Bitmap(new System.IO.MemoryStream(new System.Net.WebClient().DownloadData(Dominio_ReceitaFederal + UrlImagemCaptcha)));
            }
            else
            {
                viewState = "";
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {

            WebRequest request = WebRequest.Create(Dominio_ReceitaFederal + PostData_ReceitaFederal);

            // Formatando o ViewState Recebido
            string fviewstate = viewState;
            fviewstate = System.Uri.EscapeDataString(System.Uri.UnescapeDataString(fviewstate));

            // inserindo os campos a serem postados
            string postData = "";
            postData = postData + "origem=comprovante&";
            postData = postData + "viewstate=" + fviewstate + "&";
            postData = postData + "cnpj=00000000000000&";
            postData = postData + "captcha=000000&";
            postData = postData + "captchaAudio=&";
            postData = postData + "submit1=Consultar&";
            postData = postData + "search_type=cnpj";

            // montando a requisicao

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);           
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();           
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();

            // ---------- erro aqui !!!
            // retorno da sefaz ---- sempre retorna -- Parametros Inválidos
            Console.WriteLine(responseFromServer);

            reader.Close();
            dataStream.Close();
            response.Close();
        }

    }
}

答案 2 :(得分:0)

您必须确保目标网站支持您尝试执行的请求。

如果没有,那你就不走运了。请记住,Web应用程序实现是决定规则的人,而不是你。

此外,您似乎正在尝试从巴西政府网站获取信息。通常,此类网站具有阻止您尝试实现的内容的机制,例如captchas和域验证。

好消息是,政府网站通常也会发布有关如何访问公共网络服务的规则和手册。但是,您通常也需要获得许可。

答案 3 :(得分:0)

该页面使用框架:

<frame name="top" scrolling="no"  frameborder="0" marginheight="0" noresize="true" target="contents" src="cabecalho.htm" marginwidth="0" marginheight="0">
<frame  frameborder="0" name="main" SRC="cnpjreva_solicitacao2.asp" scrolling="auto" noresize="false" marginheight="0"  marginwidth="0">

框架包含 cnpjreva_solicitacao2.asp 页面,因此请致电http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao2.asp?cnpj=00495835000160(请参阅页面中的 2 文件名)将显示主框架的内容,CNPJ填充为参数传递。

答案 4 :(得分:0)

我说的不是制作生成的代码, 你可以注入javascript。

e.g。 打开您发布的页面 http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp

打开JS Console并输入以下内容:

document.getElementsByName("main")[0].contentDocument.getElementsByName("cnpj")[0].value = "MyNewValue"

请注意,表单位于frame元素内,因此您需要获取frame元素,然后获取input元素。

您可以通过Web浏览器API执行相同的操作。

解决CAPTCHA的好运