Здравствуйте, kov_serg
PHP to C# онлайн выдал:
using System;
using System.IO;
using System.Net;
using System.Text.Json;
using HtmlAgilityPack;
class Program
{
static void Main()
{
// string url = "https://apnews.com/politics";
string url = "https://apnews.com/sports";
string userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36";
string cfgFn = "config.json";
if (!File.Exists(cfgFn))
{
var processInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = "python3",
Arguments = $"main.py https://apnews.com/ -v -d -f {cfgFn} --user-agent='{userAgent}'",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
var process = System.Diagnostics.Process.Start(processInfo);
process.WaitForExit();
}
var cfg = JsonSerializer.Deserialize<Config>(File.ReadAllText(cfgFn));
userAgent = cfg.ClearanceCookies[0].UserAgent;
string cfClearance = cfg.ClearanceCookies[0].CfClearance;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.UserAgent = userAgent;
request.Headers.Add("Cookie", $"cf_clearance={cfClearance}");
string htmlContent;
using (var response = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
htmlContent = reader.ReadToEnd();
}
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlContent);
var titles = htmlDoc.DocumentNode.SelectNodes("//div[contains(@class, 'PagePromo-title')]");
if (titles == null)
{
File.Delete(cfgFn);
Console.WriteLine("fail");
return;
}
int i = 0;
foreach (var title in titles)
{
string newsText = title.InnerText.Trim();
string newsUrl = string.Empty;
var link = title.SelectSingleNode(".//a");
if (link != null) newsUrl = link.GetAttributeValue("href", string.Empty);
Console.WriteLine($"{++i,2}. {newsText}");
}
}
public class Config
{
public ClearanceCookie[] ClearanceCookies { get; set; }
}
public class ClearanceCookie
{
public string UserAgent { get; set; }
public string CfClearance { get; set; }
}
}
На строке var cfg = JsonSerializer.Deserialize<Config>(File.ReadAllText(cfgFn)); ошибка во время выполнения: пишет, что нет файла config.json. Совсем разработчики PHP to C# обленились, не могут нормальный код выдать)). Как бы исправить?)