diff --git a/ALGORITMS/.idea/shelf/Uncommitted_changes_before_Update_at_02_08_2021_4_04__Default_Changelist_.xml b/ALGORITMS/.idea/shelf/Uncommitted_changes_before_Update_at_02_08_2021_4_04__Default_Changelist_.xml new file mode 100644 index 0000000..5089337 --- /dev/null +++ b/ALGORITMS/.idea/shelf/Uncommitted_changes_before_Update_at_02_08_2021_4_04__Default_Changelist_.xml @@ -0,0 +1,4 @@ + + \ No newline at end of file diff --git a/ALGORITMS/Lesson_6/1.py b/ALGORITMS/Lesson_6/1.py new file mode 100644 index 0000000..5ee66a8 --- /dev/null +++ b/ALGORITMS/Lesson_6/1.py @@ -0,0 +1,30 @@ +''' +1. Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков. +Проанализировать результат и определить программы с наиболее эффективным использованием памяти. +Примечание: Для анализа возьмите любые 1-3 ваших программы или несколько вариантов кода для одной и той же задачи. +Результаты анализа вставьте в виде комментариев к коду. Также укажите в комментариях версию Python и разрядность вашей ОС. +''' + +import sys + +res = {} +for i in range(2, 10): + res[i] = [] + for j in range(2, 100): + if j % i == 0: + res[i].append(j) + print(f'Числу {i} кратны {len(res[i])} чисел: {res[i]}') + + +sum_size = 0 +sum_size1 = 0 +sum_size2 = 0 +sum_size += sys.getsizeof(i) +sum_size1 += sys.getsizeof(print) +sum_size2 += sys.getsizeof(res) + +print('\nПеременные занимают:', sum_size, sum_size1, sum_size2) + +''' +Переменные занимают: 28 72 360 +''' diff --git a/JS/Lesson_1/3_4_.txt b/JS/Lesson_1/3_4_.txt new file mode 100644 index 0000000..9292e9c --- /dev/null +++ b/JS/Lesson_1/3_4_.txt @@ -0,0 +1,10 @@ +3. Чему будет равно JS-выражение 1000 + "108" + Так как 1000 - число, + а '108' - строка, то выражение будет равно '1000108' + +4. Самостоятельно разобраться с атрибутами тега script (async и defer) + async подключает скрипты асинхронно, + defer тоже подключает их асинхронно, + но в более строгой последовательности. + Они как бы не блокируют html страничку во время загрузки, а параллельно грузятся + diff --git a/JS/Lesson_1/example_1.js b/JS/Lesson_1/example_1.js new file mode 100644 index 0000000..1700427 --- /dev/null +++ b/JS/Lesson_1/example_1.js @@ -0,0 +1,4 @@ +let с = prompt('Задайте температуру в градусах по Цельсию: ') +let f = (9 / 5) * с + 32 +alert(`Температура в фаренгейтах: ${f}`) + diff --git a/JS/Lesson_1/example_2.js b/JS/Lesson_1/example_2.js new file mode 100644 index 0000000..924d38c --- /dev/null +++ b/JS/Lesson_1/example_2.js @@ -0,0 +1,3 @@ +let name = 'Василий' +let admin = name +console.log(admin) diff --git a/JS/Lesson_2/1.txt b/JS/Lesson_2/1.txt new file mode 100644 index 0000000..5f0a9fa --- /dev/null +++ b/JS/Lesson_2/1.txt @@ -0,0 +1,15 @@ +1. Дан код: + +var a = 1, b = 1, c, d; +c = ++a; alert(c); // 2; 1 + 1 (c = 2), (a = 2) +d = b++; alert(d); // 1; (b = 1) + (d = undefined), (d = 1), (b = 2) +c = (2+ ++a); alert(c); // 5; 2 + (2 + 1) (c = 5), (a = 3) +d = (2+ b++); alert(d); // 4; 1 + 2 + 1 (d = 4), (b = 3) +alert(a); // 3; a = 3 +alert(b); // 3; b = 3 + +++a +инкремент сначала срабатывает, а потом возвращает число + +a++ +сначала возвращается число, а потом срабатывает инкремент \ No newline at end of file diff --git a/JS/Lesson_2/2.txt b/JS/Lesson_2/2.txt new file mode 100644 index 0000000..2ead0e3 --- /dev/null +++ b/JS/Lesson_2/2.txt @@ -0,0 +1,9 @@ +2. Чему будет равен x в примере ниже? + +var a = 2; +var x = 1 + (a *= 2); + +a = 2 +1 + (2 * 2) = 5 + +Ответ: x равен 5 \ No newline at end of file diff --git a/JS/Lesson_2/3.txt b/JS/Lesson_2/3.txt new file mode 100644 index 0000000..d15b446 --- /dev/null +++ b/JS/Lesson_2/3.txt @@ -0,0 +1,113 @@ + 3. Объявить две целочисленные переменные a и b и задать им произвольные начальные значения. + Затем написать скрипт, который работает по следующему принципу: + если a и b положительные, вывести их разность; + если а и b отрицательные, вывести их произведение; + если а и b разных знаков, вывести их сумму; ноль можно считать положительным числом. + + +const a = Math.floor(Math.random() * (10 - -10) + -10) +const b = Math.floor(Math.random() * (10 - -10) + -10) +if (a > 0 && b > 0) console.log(a - b) +if (a < 0 && b < 0) console.log(a * b) +if ((a >= 0 && b < 0) || (a < 0 && b >= 0)) console.log(a + b) + + + 4. Присвоить переменной а значение в промежутке [0..15]. + С помощью оператора switch организовать вывод чисел от a до 15. + +const a = Math.floor(Math.random() * (15 - 0) + 0) + +switch (a) { + case 0: + console.log(0); + case 1: + console.log(1); + case 2: + console.log(2); + case 3: + console.log(3); + case 4: + console.log(4); + case 5: + console.log(5); + case 6: + console.log(6); + case 7: + console.log(7); + case 8: + console.log(8); + case 9: + console.log(9); + case 10: + console.log(10); + case 11: + console.log(11); + case 12: + console.log(12); + case 13: + console.log(13); + case 14: + console.log(14); + case 15: + console.log(15); +} + + + 5. Реализовать основные 4 арифметические операции в виде функций с двумя параметрами. + Обязательно использовать оператор return. + +let a = 10 +let b = 5 + +function plus(a, b){ + return a + b; +} + +function minus(a, b){ + return a - b; +} + +function div (a, b){ + return a / b; +} + +function mult (a, b){ +return a * b; +} + +console.log(plus(a, b)) +console.log(minus(a, b)) +console.log(div(a, b)) +console.log(mult(a, b)) + + + 6. Реализовать функцию с тремя параметрами: function mathOperation(arg1, arg2, operation), + где arg1, arg2 – значения аргументов, operation – строка с названием операции. + В зависимости от переданного значения операции выполнить одну из арифметических операций (использовать функции из пункта 3) + и вернуть полученное значение (использовать switch). + +function mathOperation(arg1, arg2, operation){ + switch(operation){ + case 'сложение': + return arg1 + arg2; + case 'вычитание': + return arg1 - arg2; + case 'деление': + return arg1 / arg2; + case 'умножение': + return arg1 * arg2; + } +} + + 7. *Сравнить null и 0. Попробуйте объяснить результат. + + null это что-то несуществующее, поэтому он не равен ничему, он и не true, и не false + + 8. *С помощью рекурсии организовать функцию возведения числа в степень. + Формат: function power(val, pow), где val – заданное число, pow – степень. + +function power(val, pow){ + if (pow <=0) return + if (pow === 1) return val + return val * power(val, pow - 1) +} diff --git a/JS/Lesson_3/1.txt b/JS/Lesson_3/1.txt new file mode 100644 index 0000000..76d1134 --- /dev/null +++ b/JS/Lesson_3/1.txt @@ -0,0 +1,35 @@ +1. С помощью цикла while вывести все простые числа в промежутке от 0 до 100 + +for (let i = 2; i <= 100; i++) { + let prime_number = true; + for (let j = 2; j < i; j++) { + if ((i % j) === 0) { + prime_number = false; + break + } + } + + if (prime_number) { + console.log(i) + } +} + +//================================================= + +let i = 2 +while (i < 100) { + let prime_number = true + let j = 2 + + while (j < i) { + if (i % j === 0) { + prime_number = false + break + } + j++ + } + if (prime_number) { + console.log(i) + } + i++ +} diff --git a/JS/Lesson_3/2.txt b/JS/Lesson_3/2.txt new file mode 100644 index 0000000..c209459 --- /dev/null +++ b/JS/Lesson_3/2.txt @@ -0,0 +1,2 @@ +2. С этого урока начинаем работать с функционалом интернет-магазина. Предположим, есть сущность корзины. +Нужно реализовать функционал подсчета стоимости корзины в зависимости от находящихся в ней товаров. \ No newline at end of file diff --git a/JS/Lesson_3/3.txt b/JS/Lesson_3/3.txt new file mode 100644 index 0000000..31cf4af --- /dev/null +++ b/JS/Lesson_3/3.txt @@ -0,0 +1,26 @@ +3. Товары в корзине хранятся в массиве. Задачи: +a) Организовать такой массив для хранения товаров в корзине; +b) Организовать функцию countBasketPrice, которая будет считать стоимость корзины. + + +let basket = [ + { name: 'Стол', price: 5500 }, + { name: 'Ноутбук', price: 72000 } +] + +function countBasketPrice(basket) { + let basketPrice = 0 + for (let prod of basket){ + basketPrice += prod.price + } + return basketPrice +} + +console.log("Стоимость корзины: " + countBasketPrice(basket) + " руб.") + + + +let basketPrice = 0 +basket.forEach(el => basketPrice += el.price) +console.log("Стоимость корзины: " + basketPrice + " руб.") +return basketPrice diff --git a/JS/Lesson_3/4.txt b/JS/Lesson_3/4.txt new file mode 100644 index 0000000..81cfa76 --- /dev/null +++ b/JS/Lesson_3/4.txt @@ -0,0 +1,5 @@ +4.*Вывести с помощью цикла for числа от 0 до 9, не используя тело цикла. Выглядеть это должно так: +for(…){// здесь пусто} + + +for (i = 0; i <= 9; console.log(i++)) {} \ No newline at end of file diff --git a/JS/Lesson_3/5.txt b/JS/Lesson_3/5.txt new file mode 100644 index 0000000..760e63c --- /dev/null +++ b/JS/Lesson_3/5.txt @@ -0,0 +1,20 @@ +5. *Нарисовать пирамиду с помощью console.log, как показано на рисунке, только у вашей пирамиды должно быть 20 рядов, а не 5: +x +xx +xxx +xxxx +xxxxx + + + +let row = 'x'; +for (let i = 0; i < 20; i++) { + console.log(row); + row += 'x'; +} + + +for (let i = 0; i < 20; i++) { + let res = new Array(i).fill('x') + console.log(res.join('')) +} \ No newline at end of file diff --git a/JS/Lesson_4/1.txt b/JS/Lesson_4/1.txt new file mode 100644 index 0000000..b089363 --- /dev/null +++ b/JS/Lesson_4/1.txt @@ -0,0 +1,31 @@ +1. Написать функцию, преобразующую число в объект. Передавая на вход число от 0 до 999, + надо получить на выходе объект, в котором в соответствующих свойствах описаны + единицы, десятки и сотни. Например, для числа 245 надо получить следующий объект: + {‘единицы’: 5, ‘десятки’: 4, ‘сотни’: 2}. Если число превышает 999, необходимо + выдать соответствующее сообщение с помощью console.log и вернуть пустой объект. + + +function f(n) { + if (n > 999) { + console.log('число больше 999'); + return {} + } + if (n < 0) { + console.log('число меньше 0'); + return {} + } + + const arr = String(n).split('') + const len = arr.length + + return { + сотни: len === 3 ? +arr[0] : 0, + десятки: len === 1 ? 0 : +arr[len - 2], + единицы: +arr[len - 1] + } +} + +console.log(f(28)) +console.log(f(574)) +console.log(f(1000)) +console.log(f(-5)) \ No newline at end of file diff --git a/JS/Lesson_4/2.txt b/JS/Lesson_4/2.txt new file mode 100644 index 0000000..20893b9 --- /dev/null +++ b/JS/Lesson_4/2.txt @@ -0,0 +1,56 @@ +2. Продолжить работу с интернет-магазином: +В прошлом домашнем задании вы реализовали корзину на базе массивов. Какими объектами можно заменить их элементы? +Реализуйте такие объекты. +Перенести функционал подсчета корзины на объектно-ориентированную базу. + + +class Cart { + constructor(personName, cart) { + this.personName = personName + this.cart = [] + } + + addToCart({id, name, description, price}) { + this.cart.push({id, name, description, price}) + } + + itemCount() { + return this.cart.length + } + + cartPrice() { + let res = 0 + this.cart.forEach(el => res += el.price) + return res + } +} + +const Person = new Cart('Ivan Ivanov', []) + +const item1 = { + id: 1, + name: 'First item', + description: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.', + price: 500 +} +const item2 = { + id: 2, + name: 'Second item', + description: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.', + price: 750 +} +const item3 = { + id: 3, + name: 'Third item', + description: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.', + price: 300 +} + +Person.addToCart(item1) +Person.addToCart(item2) +Person.addToCart(item3) + + +console.log(Person) +console.log(Person.cartPrice()) +console.log(Person.itemCount()) diff --git a/JS/Lesson_5/1/index.html b/JS/Lesson_5/1/index.html new file mode 100644 index 0000000..bb77be8 --- /dev/null +++ b/JS/Lesson_5/1/index.html @@ -0,0 +1,15 @@ + + + + + + + + Document + + + + + + + \ No newline at end of file diff --git a/JS/Lesson_5/1/main.js b/JS/Lesson_5/1/main.js new file mode 100644 index 0000000..da374dd --- /dev/null +++ b/JS/Lesson_5/1/main.js @@ -0,0 +1,25 @@ +let field = document.createElement('DIV'); +document.body.appendChild(field); + +for (let y = 0; y < 10; y++) { + for (let x = 0; x < 10; x++) { + let css = x ? {} : { clear: 'left' }; + let content = ''; + if (y == 0 || y == 9) + content = x > 0 && x < 9 ? 'ABCDEFGH'.charAt(x - 1) : null; + else if (x == 0 || x == 9) + content = 9 - y; + else css.background = (x + y) % 2 ? '#000' : '#fff'; + + let node = document.createElement('DIV'); + css.width = '50px'; + css.height = css.width; + css.textAlign = 'center'; + css.lineHeight = '50px' + css.float = 'left'; + for (let i in css) node.style[i] = css[i]; + if (content) + node.innerHTML = content; + field.appendChild(node); + } +} diff --git "a/JS/Lesson_5/1/\320\227\320\260\320\264\320\260\321\207\320\260_1.txt" "b/JS/Lesson_5/1/\320\227\320\260\320\264\320\260\321\207\320\260_1.txt" new file mode 100644 index 0000000..bd97b95 --- /dev/null +++ "b/JS/Lesson_5/1/\320\227\320\260\320\264\320\260\321\207\320\260_1.txt" @@ -0,0 +1,3 @@ +Создать функцию, генерирующую шахматную доску. Можно использовать любые html-теги. +Доска должна быть верно разлинована на черные и белые ячейки. Строки должны нумероваться числами от 1 до 8, +столбцы — латинскими буквами A, B, C, D, E, F, G, H. diff --git a/JS/Lesson_5/2/index.html b/JS/Lesson_5/2/index.html new file mode 100644 index 0000000..c905043 --- /dev/null +++ b/JS/Lesson_5/2/index.html @@ -0,0 +1,3 @@ + +
+ \ No newline at end of file diff --git a/JS/Lesson_5/2/main.js b/JS/Lesson_5/2/main.js new file mode 100644 index 0000000..7329bfe --- /dev/null +++ b/JS/Lesson_5/2/main.js @@ -0,0 +1,16 @@ +const root = document.getElementById('root') + +const cart = [ + {name: 'product_1', price: 5}, + {name: 'product_2', price: 15}, + {name: 'product_3', price: 34} +] + +let sum = 0 + +if (cart.length === 0) { + root.textContent = 'Корзина пуста' +} else { + cart.forEach(el => sum += el.price) + root.textContent = `В корзине: ${cart.length} товаров на сумму ${sum}` +} \ No newline at end of file diff --git "a/JS/Lesson_5/2/\320\227\320\260\320\264\320\260\321\207\320\260_2.txt" "b/JS/Lesson_5/2/\320\227\320\260\320\264\320\260\321\207\320\260_2.txt" new file mode 100644 index 0000000..dd94a97 --- /dev/null +++ "b/JS/Lesson_5/2/\320\227\320\260\320\264\320\260\321\207\320\260_2.txt" @@ -0,0 +1,4 @@ +Сделать генерацию корзины динамической: верстка корзины не должна находиться в HTML-структуре. +Там должен быть только div, в который будет вставляться корзина, сгенерированная на базе JS: +Пустая корзина должна выводить строку «Корзина пуста»; +Наполненная должна выводить «В корзине: n товаров на сумму m рублей». diff --git a/JS/Lesson_5/3/index.html b/JS/Lesson_5/3/index.html new file mode 100644 index 0000000..c905043 --- /dev/null +++ b/JS/Lesson_5/3/index.html @@ -0,0 +1,3 @@ + +
+ \ No newline at end of file diff --git a/JS/Lesson_5/3/main.js b/JS/Lesson_5/3/main.js new file mode 100644 index 0000000..8d27474 --- /dev/null +++ b/JS/Lesson_5/3/main.js @@ -0,0 +1,35 @@ +const root = document.getElementById('root') + +let list = [] + +class Product { + constructor(name, price, description) { + this.name = name + this.price = price + this.description = description + } + + add() { + list.push(this) + } + + toHTML() { + return ` +
+

${this.name}

+

${this.price}

+

${this.description}

+
+ ` + } +} + +const car = new Product('BMW', 25000, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.') +const mac = new Product('Apple', 2700, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.') +const phone = new Product('iPhone', 900, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.') + +car.add() +mac.add() +phone.add() + +root.innerHTML = list.map(el => el.toHTML()).join('') \ No newline at end of file diff --git "a/JS/Lesson_5/3/\320\227\320\260\320\264\320\260\321\207\320\260_3.txt" "b/JS/Lesson_5/3/\320\227\320\260\320\264\320\260\321\207\320\260_3.txt" new file mode 100644 index 0000000..52b4be9 --- /dev/null +++ "b/JS/Lesson_5/3/\320\227\320\260\320\264\320\260\321\207\320\260_3.txt" @@ -0,0 +1,5 @@ +* Сделать так, чтобы товары в каталоге выводились при помощи JS: +Создать массив товаров (сущность Product); +При загрузке страницы на базе данного массива генерировать вывод из него. +HTML-код должен содержать только div id=”catalog” без вложенного кода. +Весь вид каталога генерируется JS. diff --git a/PARSING/Lesson_1/1.py b/PARSING/Lesson_1/1.py new file mode 100644 index 0000000..4188b66 --- /dev/null +++ b/PARSING/Lesson_1/1.py @@ -0,0 +1,15 @@ +import requests +import json + + +url = 'https://api.github.com' +user = 'softicer-67' + + +request = requests.get(f'{url}/users/{user}/repos') + +js = request.json() +for i in range(0, len(js)): + res = f'Project Number: {i + 1}\nProject Name: {js[i]["name"]}\nProject URL: {js[i]["svn_url"]}' + print(res) + diff --git a/PARSING/Lesson_3/1.py b/PARSING/Lesson_3/1.py new file mode 100644 index 0000000..2817cf3 --- /dev/null +++ b/PARSING/Lesson_3/1.py @@ -0,0 +1,41 @@ +''' +1. Развернуть у себя на компьютере/виртуальной машине/хостинге MongoDB и реализовать функцию, +записывающую собранные вакансии в созданную БД. +''' + +import requests +from bs4 import BeautifulSoup as bs +import pandas as pd +import csv +from pymongo import MongoClient + +header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'} + + +def get_data(zp): + resp = requests.get(f'https://www.rabota.ru/?sort=relevance&min_salary={zp}', headers=header) + soup = bs(resp.text, 'lxml') + result = [] + work = soup.find_all(class_="vacancy-preview-card__title") + price = soup.find_all(class_="vacancy-preview-card__salary vacancy-preview-card__salary-blue") + for i in range(20): + result.append({ + 'Вакансия': work[i].text.strip(), + 'Зарплата': price[i].text.strip().replace('\xa0', ' ') + }) + print(result[i]) + pd.DataFrame(result).to_csv('dump.csv') + + +def to_mongo(): + client = MongoClient('localhost') + db = client["test01"] + col = db["work"] + with open('dump.csv', 'r', encoding='utf-8') as read_obj: + csv_reader = csv.DictReader(read_obj) + mylist = csv_reader + col.insert_many(mylist) + + +get_data(80000) # Требуемая зарплата +to_mongo() diff --git a/PARSING/Lesson_3/2.py b/PARSING/Lesson_3/2.py new file mode 100644 index 0000000..fd27286 --- /dev/null +++ b/PARSING/Lesson_3/2.py @@ -0,0 +1,32 @@ +''' +2. Написать функцию, которая производит поиск и выводит на экран вакансии +с заработной платой больше введённой суммы. +''' + +import requests +from bs4 import BeautifulSoup as bs +from pprint import pprint + + +header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'} +url = 'https://www.rabota.ru' + + +def get_data(zp): + resp = requests.get(f'https://www.rabota.ru/?sort=relevance&min_salary={zp}', headers=header) + soup = bs(resp.text, 'lxml') + result = [] + work = soup.find_all(class_="vacancy-preview-card__title") + link = soup.find_all(class_='vacancy-preview-card__title') + price = soup.find_all(class_="vacancy-preview-card__salary vacancy-preview-card__salary-blue") + for i in range(20): + result.append({ + 'Вакансия': work[i].text.strip(), + 'Зарплата': price[i].text.strip().replace('\xa0', ' '), + 'Ссылка': url + link[i].find('a').get('href') + }) + pprint(result[i]) + print('-' * 90) + + +get_data(80000) # Требуемая зарплата diff --git a/PARSING/Lesson_3/3.py b/PARSING/Lesson_3/3.py new file mode 100644 index 0000000..3d347cf --- /dev/null +++ b/PARSING/Lesson_3/3.py @@ -0,0 +1,4 @@ +''' +3. Написать функцию, которая будет добавлять в вашу базу данных только новые вакансии с сайта. +''' + diff --git a/PARSING/Lesson_3/base.png b/PARSING/Lesson_3/base.png new file mode 100644 index 0000000..11734bf Binary files /dev/null and b/PARSING/Lesson_3/base.png differ diff --git a/PARSING/Lesson_3/dump.csv b/PARSING/Lesson_3/dump.csv new file mode 100644 index 0000000..a0d9f32 --- /dev/null +++ b/PARSING/Lesson_3/dump.csv @@ -0,0 +1,21 @@ +,Вакансия,Зарплата +0,Инженер ПТО (вахта),от 114 000 руб. +1,Сварщик НАКС (вахта),114 000 — 120 000 руб. +2,Геодезист,135 000 — 150 000 руб. +3,Арматурщик,100 000 — 120 000 руб. +4,Менеджер по работе с клиентами,50 000 — 150 000 руб. +5,Кладовщик-комплектовщик,69 000 — 117 000 руб. +6,Слесарь-сборщик,85 000 — 90 000 руб. +7,Слесарь механосборочных работ,70 000 — 80 000 руб. +8,Автоэлектрик,до 105 000 руб. +9,Врач-неонатолог,от 140 000 руб. +10,Машинист автогрейдера,80 000 — 100 000 руб. +11,Электросварщик РД НАКС,132 000 — 158 000 руб. +12,Стикеровщик на склад алкоголя,45 000 — 80 000 руб. +13,Инженер ПТО,от 95 000 руб. +14,Комплектовщик,90 000 — 120 000 руб. +15,Комплектовщик,90 000 — 100 000 руб. +16,Слесарь-сборщик двигателей,90 000 — 95 000 руб. +17,Сварщик арматурных каркасов,100 000 — 110 000 руб. +18,Филетировщик/ца на филе рыбы (вахта),118 000 — 129 000 руб. +19,Машинист автокрана,от 131 000 руб. diff --git a/PARSING/Lesson_4/1.py b/PARSING/Lesson_4/1.py new file mode 100644 index 0000000..af5228a --- /dev/null +++ b/PARSING/Lesson_4/1.py @@ -0,0 +1,68 @@ +''' +Написать приложение, которое собирает основные новости с сайтов mail.ru, lenta.ru, yandex-новости. +Для парсинга использовать XPath. Структура данных должна содержать: +название источника; +наименование новости; +ссылку на новость; +дата публикации. +''' + +from lxml import html +import requests +import datetime + +header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'} +now = datetime.datetime.now() +now = f"{'%d' % now.year}.{'%d' % now.month}.{'%d' % now.day}." +err = 'Ошибка запроса' + + +def request_to_mail(): + try: + response = requests.get('https://news.mail.ru/', headers=header) + root = html.fromstring(response.text) + for i in range(1, 5): + news = root.xpath(f'//*[@id="index_page"]/div[7]/div[2]/div[3]/div/div/div/div[{i}]/div/div[2]/span[2]/a/span') + link = root.xpath(f'//*[@id="index_page"]/div[7]/div[2]/div[3]/div/div/div/div[{i}]/div/div[2]/span[2]/a/@href') + ist = root.xpath(f'//*[@id="index_page"]/div[7]/div[2]/div[3]/div/div/div/div[{i}]/div/div[2]/div/span[2]/text()') + tim = root.xpath(f'//*[@id="index_page"]/div[7]/div[2]/div[3]/div/div/div/div[{i}]/div/div[2]/div/span[1]') + print([ist[0]], news[0].text, link[0], now, tim[0].text) + except: + print(err) + + +def request_to_lenta(): + try: + url = 'https://lenta.ru/' + response = requests.get('https://lenta.ru/', headers=header) + root = html.fromstring(response.text) + for i in range(5, 10): + link = root.xpath(f'//*[@id="root"]/section[2]/div/div/div[2]/div[1]/section/div/div[{i}]/a/@href') + news = root.xpath(f'//*[@id="root"]/section[2]/div/div/div[2]/div[1]/section/div/div[{i}]/a/text()') + print(news[0], url + link[0], now) + except: + print(err) + + +def request_to_yandex(): + try: + response = requests.get('https://yandex.ru/news/', headers=header) + root = html.fromstring(response.text) + for i in range(2, 6): + ist = root.xpath(f'/html/body/div[3]/div/div[2]/div/div[1]/div[1]/div[{i}]/article/div[3]/div[1]/div/span[1]/a') + link = root.xpath(f'/html/body/div[3]/div/div[2]/div/div[1]/div[1]/div[{i}]/article/div[3]/div[1]/div/span[1]/a/@href') + news = root.xpath(f'/html/body/div[3]/div/div[2]/div/div[1]/div[1]/div[{i}]/article/div[1]/div/a/h2') + tim = root.xpath(f'/html/body/div[3]/div/div[2]/div/div[1]/div[1]/div[{i}]/article/div[3]/div[1]/div/span[2]') + print([ist[0].text], news[0].text, link[0], now, tim[0].text) + except: + print(err) + + +print('\tnews.mail.ru'.upper()) +request_to_mail() +print('=' * 145) +print('\tlenta.ru'.upper()) +request_to_lenta() +print('=' * 145) +print('\tyandex.ru/news'.upper()) +request_to_yandex()