如何解决C# 从 url 获取 html错误 (429) 未知
我正在使用以下代码从 url 中检索 html 代码。它适用于以下网址:
- https://trends.google.com/trends/?geo=US 但是,不适用于下一个,返回错误为
“远程服务器返回错误:(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();
}
}
解决方法
如果没有 API,就无法再获取 google 服务的源代码,因为特别是当您仅访问 trends.google.es/trends/explore?q=test 时,trends 服务会进行很多调用因此错误 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 代码
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。