Загрузка...

Pars and graphQL

Thread in C# created by Minin_inactive4471240 Dec 24, 2022. 398 views

  1. Minin_inactive4471240
    Minin_inactive4471240 Topic starter Dec 24, 2022 3 Sep 5, 2021
    Всем привет, помогите, пожалуйста, спарсить инфу с сайта, на котором стоит graphQL сайт

    вот я пытался набросать код, но, всё тщетно...
    CSHARP
    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;
    using GraphQL.Client;
    using GraphQL.Client.Http;
    using GraphQL.Client.Abstractions;
    using GraphQL.Client.Http.Websocket;
    using GraphQL.Client.Abstractions.Utilities;
    using GraphQL.Client.Abstractions.Websocket;
    using GraphQL;
    using GraphQL.Client.Serializer.Newtonsoft;
    using Newtonsoft.Json.Linq;
    using System.Net;

    namespace Yola
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
    public class MyClass
    {
    public string data { get; set; }
    public string feed { get; set; }
    public string items { get; set; }
    public string a { get; set; }
    public string prod { get; set; }
    public string id { get; set; }
    }

    //async Task ExeсuteParseCommand()
    //{


    //}

    private async void Do()
    {
    await Task.Factory.StartNew(() =>
    {
    var query = @"query{data{feed{items{0{product{id}}}}}}";
    try
    {
    var client = new GraphQLHttpClient("https://api-gw.youla.io/federation/graphql", new NewtonsoftJsonSerializer());
    //var cleint = new GraphQLHttpClient(new GraphQLHttpClientOptions
    //{
    // EndPoint = new Uri(BackendConstants.GraphQLApiUrl)
    //});

    var request = new GraphQLRequest() { Query = query };
    var response = client.SendQueryAsync<MyClass>(request);

    var alo = response.IsCompleted;
    var aloalo = response.Result;

    for (int i = 0; i < 100; i++)
    {
    MessageBox.Show(aloalo[i].ToString());
    }


    MessageBox.Show("УСПЕЕЕЕЕЕХ!!!");
    MessageBox.Show(response.ToString());

    }
    catch (Exception ex)
    {
    MessageBox.Show("ERROR!!!");
    MessageBox.Show(ex.ToString() + "ОШИИИИИИБКААААА!!!!!!!");

    }
    });
    }


    //private async void Do()
    //{
    // await Task.Factory.StartNew(() =>
    // {
    // var query = @"query{data{feed{items{0{product{id}}}}}}";
    // try
    // {
    // var graphQLClient = new GraphQLClient("https://api-gw.youla.io/federation/graphql")
    // //var cleint = new GraphQLHttpClient(new GraphQLHttpClientOptions
    // //{
    // // EndPoint = new Uri(BackendConstants.GraphQLApiUrl)
    // //});

    // var request = new GraphQLRequest() { Query = query };
    // var response = client.SendQueryAsync<MyClass>(request);

    // var alo = response.IsCompleted;
    // var aloalo = response.Result;

    // for (int i = 0; i < 100; i++)
    // {
    // MessageBox.Show(aloalo[i].ToString());
    // }


    // MessageBox.Show("УСПЕЕЕЕЕЕХ!!!");
    // MessageBox.Show(response.ToString());

    // }
    // catch (Exception ex)
    // {
    // MessageBox.Show("ERROR!!!");
    // MessageBox.Show(ex.ToString() + "ОШИИИИИИБКААААА!!!!!!!");

    // }
    // });
    //}


    public async void button1_Click(object sender, EventArgs e)
    {
    //var i = await ExeсuteParseCommand();

    Do();

    }


    }
    }
    Для работы с graphQL устанавливал эти либы [IMG]
     
  2. ёклмн
    ёклмн Dec 24, 2022 Banned 1 May 22, 2022
    [IMG]
    выяснили что ошибка изза невалидного запроса в переменной query, помогите человеку
     
  3. FSnikers
    FSnikers Dec 24, 2022 13 Dec 2, 2016
    var request = new GraphQLRequest() { Query = query };

    Он принимает запрос через конструктор, попробуй через него, конечно вряд-ли это поможет, но все же, либо скачать сниффер и проверь корректность через него.
    var request = new GraphQLRequest(query);
     
  4. vtlstolyarov
    Minin_inactive4471240, Когда загружается страница с сайта которую ты укзал в теме там выполняется 2 GraphQL запроса:
    JSON
    {"operationName":"catalogProductsBoard","variables":{"sort":"DEFAULT","attributes":[{"slug":"price","value":null,"from":150000,"to":null},{"slug":"categories","value":["zhenskaya-odezhda"],"from":null,"to":null}],"datePublished":{"to":1672008625,"from":1671922225},"location":{"latitude":null,"longitude":null,"city":null,"distanceMax":null},"search":"","cursor":""},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"6e7275a709ca5eb1df17abfb9d5d68212ad910dd711d55446ed6fa59557e2602"}}}
    и
    JSON
    {"operationName":"FilterCatalogContextFieldQuery","variables":{"categoryId":9,"subcategoryId":null,"attributeItems":[{"slug":"price","value":null,"from":150000,"to":null}]},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"6921c323cf1ed130fb140169950bfa5e7b2c31003c733b89bc4cbb12c6f359eb"}}}
    запрос который ты пытаешься сделать в своём коде даже близко не похож ни на один из них - где ты его взял? Я подозреваю что ты хочешь получить первый запрос так как поля в его ответе похожи на те что ты описал в MyClass.
     
  5. vtlstolyarov
    Minin_inactive4471240, Я никогда не работал с GraphQL но вроде такой код должен сработать (если конечно если я правильно понял что ты хотел сделать);

    CSHARP
    using System;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    namespace Yola
    {
    public partial class Form1 : Form
    {
    private readonly ApiClient _apiClient = new ApiClient();

    public Form1()
    {
    InitializeComponent();
    }

    public async void button1_Click(object sender, EventArgs e)
    {
    try
    {
    var products = await _apiClient.GetProducts();
    MessageBox.Show("УСПЕЕЕЕЕЕХ!!!");

    foreach (var product in products)
    {
    MessageBox.Show($"{product.id} {product.name}");
    }
    }
    catch (Exception ex)
    {
    MessageBox.Show("ERROR!!!");
    MessageBox.Show(ex.ToString() + "ОШИИИИИИБКААААА!!!!!!!");
    }
    }
    }
    }
    ну и код API клиентов всё же лучше отделять от UI кода (я там оставил захардкоженные параметры запроса которые взял из браузера - их по-хорошему надо бы заменить на параметры для метода GetProducts. sha256Hash скорее всего надо будет пересчитывать для параметризированного запроса):
    CSHARP
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using GraphQL;
    using GraphQL.Client.Http;
    using GraphQL.Client.Serializer.Newtonsoft;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;

    namespace Yola
    {
    public class Product
    {
    public string id { get; set; }
    public string name { get; set; }
    }


    public class ApiClient
    {
    private class CatalogProductsBoard
    {
    public Feed feed { get; set; }
    }

    private class Feed
    {
    public Item[] items { get; set; }
    }

    private class Item
    {
    }

    private class ProductItem : Item
    {
    public Product product { get; set; }
    }

    private class FeedItemConverter : TypenameConverter<Item>
    {
    protected override Type GetType(string typename) => typename switch
    {
    nameof(ProductItem) => typeof(ProductItem),
    _ => typeof(Item)
    };
    }

    private abstract class TypenameConverter<T> : JsonConverter<T>
    {
    protected abstract Type GetType(string typename);

    public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
    var obj = JObject.Load(reader);

    var type = GetType((string)obj["__typename"]);
    if (type == typeof(T))
    {
    return default;
    }

    return (T)obj.ToObject(type);
    }

    public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
    {
    throw new NotSupportedException();
    }
    }

    private static readonly GraphQLHttpClient GraphQLClient = new GraphQLHttpClient(
    "https://api-gw.youla.io/federation/graphql",
    new NewtonsoftJsonSerializer(settings => settings.Converters.Add(new FeedItemConverter())));

    public async Task<Product[]> GetProducts()
    {
    var response = await GraphQLClient.SendQueryAsync<CatalogProductsBoard>(new GraphQLRequest()
    {
    OperationName = "catalogProductsBoard",
    Variables = new
    {
    sort = "DEFAULT",
    attributes = new object[]
    {
    new
    {
    slug = "price",
    value = default(object),
    from = 150000,
    to = default(object)
    },
    new
    {
    slug = "categories",
    value = new []
    {
    "zhenskaya-odezhda",
    },
    from = default(object),
    to = default(object)
    }
    },
    datePublished = new
    {
    to = 1672008625,
    from = 1671922225
    },
    location = new
    {
    latitude = default(object),
    longitude = default(object),
    city = default(object),
    distanceMax = default(object)
    },
    search = "",
    cursor = ""
    },
    Extensions = new
    {
    persistedQuery = new
    {
    version = 1,
    sha256Hash = "6e7275a709ca5eb1df17abfb9d5d68212ad910dd711d55446ed6fa59557e2602"
    }
    }
    });

    return response.Data.feed.items
    .OfType<ProductItem>()
    .Select(item => item.product)
    .ToArray();
    }
    }
    }
     
Loading...
Top