C# 从 url 获取 html。错误 (429) 未知

问题描述 投票:0回答:2

我正在使用以下代码从 url 中检索 html 代码。它适用于以下网址:

“远程服务器返回错误:(429)未知。””

可能是什么错误或如何获取有关错误的更多信息?

private void getHtmlFromUrl() {

    string urlAddress = "https://trends.google.es/trends/explore?q=test&geo=US";

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream receiveStream = response.GetResponseStream();
        StreamReader readStream = null;

        if (String.IsNullOrWhiteSpace(response.CharacterSet))
            readStream = new StreamReader(receiveStream);
        else
            readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

        string htmlData = readStream.ReadToEnd();

        response.Close();
        readStream.Close();
    }

}
c# httpwebrequest httpwebresponse
2个回答
1
投票

如果没有 API,将无法再获取谷歌服务的源代码,因为特别是当您仅访问 trends.google.es/trends/explore?q=test 时,趋势服务会进行多次调用,因此出现 error 429

不要浪费时间研究代理、浏览器模拟或机器人,它们都不起作用。最好的方法是使用 Google API for c# .

示例项目:

https://github.com/thegreymatter/GoogleTrends(已弃用)

https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth(已弃用)

新的解决方案!

(我们安装 python 然后将我们的 py 脚本转换为 exe 文件以从 .net 代码使用。好消息是此方法不需要 api)

1- 安装 Python:https://www.python.org/downloads/windows/

2- 安装 Pytrends 使用:

pip install pytrends

3- 创建一个 test.py 并添加对参数的支持:

from pytrends.request import TrendReq
import sys

# Only need to run this once, the rest of requests will use the same session.
pytrend = TrendReq()
# Set your region
pytrend.geo = 'ES'
pytrend.build_payload(kw_list=[sys.argv[1]]) # Also supports an array of keywords e.g. kw_list=['test', 'music']
related_queries_dict = pytrend.related_queries()
print(related_queries_dict)
#Check the documentation for other available queries https://github.com/GeneralMills/pytrends#api-methods

现在,如果您在 test.py 的同一位置使用 cmd.exe(不使用 PowerShell 命令将无法在那里工作),请使用以下命令:

test.py test

截图结果

4- 现在让我们将 test.py 转换为 .exe(Windows 控制台文件)

(a) 安装 Pyinstaller:

pip install pyinstaller

(b) 编译test.py为test.exe

pyinstaller test.py -F

5- 您的“test.exe”位于 \dist\ 目录中。让我们看看它是否有效:

是的。 (请记住,test.exe 的文件大小为 80 MB,因为它使用了许多库。)

现在您剩下要做的就是处理。使用参数“test”启动“test.exe”文件名以读取 csharp 应用程序的输出。

您可以改用 IronPython 通过 你的 csharp 代码


0
投票

我强烈推荐 GoogleTrendsApi 包,它允许您连接到这个 Google API,并以一种非常简单的方式从中接收数据,当然与将 Python 集成到您的代码中的方式相比。

全面披露:我是它的创造者。

© www.soinside.com 2019 - 2024. All rights reserved.