Небольшая библиотека с полезными методами.

  • Автор темы Автор темы bvbfor
  • Дата начала Дата начала

bvbfor

Client
Регистрация
10.04.2016
Сообщения
507
Реакции
406
Баллы
63
Небольшая библиотека с полезными методами.​

Библиотека написана 6 лет назад с целью ускорить написание кода. Время идет, но почти все методы использую в проектах и сейчас.

138507

138508

138509

Довольно удобные методы работы с файлами.
Методы для работы с элементами браузера иногда выручают, когда не получается сделать с помощью конструктора действий.
Бывает и наоборот.

В видео ниже примеры работы нескольких методов. Если что то непонятно, описание методов можно посмотреть под спойлером выше.

​

Кто то уже привык пользоваться своими методами, для кого то поначалу может показаться сложным, или просто не понравиться.
Есть те, кто пользуется, буду рад, если кому то пригодится.

Добавляем в общий код:
Развернуть Свернуть Копировать
namespace xpath
{
    public class m
    {
        Tab ins;
        IZennoPosterProjectModel project;
        Random rand = new Random();
        Instance instance;
        string bl;
        public int pau = 0;

        public m(Tab _ins, IZennoPosterProjectModel _project, Instance _instance, int _pau = 10000)
        {
            ins = _ins;
            project = _project;
            instance = _instance;
            bl = project.Directory + @"\black.txt";
            pau = _pau;          
        }
        public bool wait(string xp, int reg = 0, int nom = 0)
        {        
            HtmlElement x1;
            int pause = pau;
            int kol = pause / 100;
            for (int i = 0; i < kol; i++)
            {
                if (reg == 0)
                {
                    x1 = ins.FindElementByXPath(xp, 0);
                }
                else
                {
                    HtmlElementCollection xx = ins.FindElementsByXPath(xp);
                    x1 = xx.GetByNumber(nom);
                }
                if (x1.IsVoid)
                    s(100);
                else
                    return true;
            }
            return false;
        }
        /// <summary>
        /// Клик по элементу
        /// </summary>
        public bool click(string xp)
        {
            mus();
            if (wait(xp))
            {
                HtmlElement x1 = ins.FindElementByXPath(xp, 0);
                x1.RiseEvent("click", "Full");
                s(500);
                pi("Удачно - " + xp);
                return true;
            }
            else
            {
                pi("не удалось кликнуть по элементу - " + xp);
                return false;
            }
        }

        public bool Col_click(string xp, int nom)
        {
            mus();
            if (wait(xp, 1, nom))
            {
                HtmlElementCollection xx = ins.FindElementsByXPath(xp);
                xx.GetByNumber(nom).RiseEvent("click", "Full");
                s(500);
                pi("удачно - " + xp);
                return true;
            }
            else
            {
                pi("не удалось кликнуть по элементу коллекции - " + xp);
                return false;
            }
        }
        public bool Col_set(string xp, int nom, string val, string attr = "innertext")
        {
            mus();
            if (wait(xp, 1, nom))
            {
                HtmlElementCollection xx = ins.FindElementsByXPath(xp);
                xx.GetByNumber(nom).SetAttribute(attr, val);
                s(500);
                pi("удачно - " + xp);
                return true;
            }
            else
            {
                pi("не удалось установить элементу коллекции - " + xp);
                return false;
            }
        }
        public bool set(string xp, string mess)
        {
            mus();
            if (wait(xp))
            {
                HtmlElement x1 = ins.FindElementByXPath(xp, 0);
                x1.SetValue(mess, "Full");
                s(500);
                pi("удачно - " + xp);
                return true;
            }
            else
            {
                pi("не удался set - " + xp);
                return false;
            }

        }
        public string get(string xp, string attr)
        {
            mus();
            if (wait(xp))
            {
                HtmlElement x1 = ins.FindElementByXPath(xp, 0);
                pi("удачно нашли - " + xp);
                return x1.GetAttribute(attr);
            }
            else
            {
                pi("не нашли get - " + xp);
                return "";
            }
        }
        public bool isElement(string xp)
        {
            HtmlElement x1 = ins.FindElementByXPath(xp, 0);
            if (wait(xp))
            {
                pi("удачно нашли - " + xp);
                return true;
            }
            else
            {
                pi("не нашли get - " + xp);
                return false;
            }
        }
        public void mus()
        {
            string nf = project.Directory + @"\musor.txt";
            if (File.Exists(nf))
            {
                string[] m = File.ReadAllLines(nf);
                for (int i = 0; i < m.Length; i++)
                {
                    HtmlElement xx = ins.FindElementByXPath(m[i].Trim(), 0);
                    if (!xx.IsVoid)
                    {
                        xx.RiseEvent("click", "Full");
                        s(500);
                    }
                }
            }
        }
        public void s(int x1, int x2)
        {
            int x = rand.Next(x1, x2);
            System.Threading.Thread.Sleep(x);
        }
        public void s(int x)
        {
            System.Threading.Thread.Sleep(x);
        }
        public void pi(string mes, bool flag = false)
        {
            try
            {
                project.SendInfoToLog(project.Variables["login"].Value + " - " + mes, flag);
            }
            catch
            {
                project.SendInfoToLog(mes, flag);
            }
        }
        public void Down(int kol)
        {
            for (int i = 0; i < kol; i++)
            {
                instance.SendText("{DOWN}", 15);
                s(500);
            }
        }
        public void Enter()
        {
            instance.SendText("{ENTER}", 15);
        }
        public void Select(string xp, int kol)
        {
            instance.WaitFieldEmulationDelay();
            instance.Click(1, 1, 1, 1, "Left", "Normal");
            click(xp);
            Down(kol);
            Enter();
        }
        public void PageDown(int kol)
        {
            for (int i = 0; i < kol; i++)
            {
                instance.SendText("{PGDN}", 15);
                s(500);
            }
        }
        public List<string> list(string xp, string attr)
        {
            string ss = "";
            mus();
            List<string> ls = new List<string>();
            HtmlElementCollection xx = ins.FindElementsByXPath(xp);
            for (int i = 0; i < xx.Count; i++)
            {
                ss = xx.GetByNumber(i).GetAttribute(attr);
                if (ss != "")
                    ls.Add(ss);
            }
            return ls;
        }
        public void AddBlack(string id)
        {
            File.AppendAllText(bl, id);
        }
        public bool ProvBlack(string id)
        {
            string ss = File.ReadAllText(bl);
            if (ss.Contains(id))
                return true;
            return false;
        }
        public int ran(int x, int y)
        {
            return rand.Next(x, y);
        }
        public string rans(int x, int y)
        {
            return rand.Next(x, y).ToString();
        }
        public string rnd_str(string fn)
        {
            string[] s = File.ReadAllLines(fn);
            int i = ran(0, s.Length);
            return s[i];
        }      
        public string rand_file(string put)
        {
            string[] imgpr = Directory.GetFiles(put);
            int nomf = ran(0, imgpr.Length - 1);
            return imgpr[nomf];
        }
        public void proxy(string nf)
        {
            if (!File.Exists(nf))
            {
                pi("Нет файла с прокси " + nf);
            }
            string[] m = File.ReadAllLines(nf);
            if (m.Length == 0)
            {
                pi("Пустой файл с прокси " + nf, true);
            }
            string prox = m[0];
            List<string> ls = new List<string>();
            ls = m.ToList();
            ls.RemoveAt(0);
            ls.Add(prox);
            File.WriteAllLines(nf, ls);
            instance.SetProxy(prox);
        }
        public string strFileEnd(string nf)
        {
            if (!File.Exists(nf))
            {
                pi("Нет файла " + nf);
                return "";
            }
            string[] m = File.ReadAllLines(nf);
            if (m.Length == 0)
            {
                pi("Пустой файл " + nf);
                return "";
            }
            string s = m[0];
            List<string> ls = new List<string>();
            ls = m.ToList();
            ls.RemoveAt(0);
            ls.Add(s);
            File.WriteAllLines(nf, ls);
            return s;
        }
        public string strFileDel(string nf)
        {
            if (!File.Exists(nf))
            {
                pi("Нет файла " + nf);
                return "";
            }
            string[] m = File.ReadAllLines(nf);
            if (m.Length == 0)
            {
                pi("Пустой файл " + nf, true);
                return "";
            }
            string s = m[0];
            List<string> ls = new List<string>();
            ls = m.ToList();
            ls.RemoveAt(0);          
            File.WriteAllLines(nf, ls);
            return s;
        }
        public bool isText(string s)
        {
            if (ins.IsBusy) ins.WaitDownloading();
            string text = ins.DomText;
            string res = "";
            var regex = new System.Text.RegularExpressions.Regex(s);
            // Поиск первого совпадения
            var match = regex.Match(text);
            if (match.Success)
                res = match.Value;
            if (res == s)
                return true;
            return false;
        }
        public string d(string nf)
        {
            string f = project.Directory + @"\" + nf;
            return f;
        }
    }
}

Шаблон из видео и doc файл со списками методов
 

Вложения

  • bibl.zip
    bibl.zip
    38 KB · Просмотры: 78
Последнее редактирование модератором:

Кто просматривает тему: (Всего: 0, Пользователи: 0, Гости: 0)