import pyshark
display_filter = 'tls.record.content_type == 22'
pcap = pyshark.FileCapture(file_path, display_filter=display_filter)
d = {}
for packet_number, packet in enumerate(pcap):
for layer in packet:
if 'Supported Version:' in str(layer):
for line in str(layer).splitlines():
if 'Supported Version:' in line:
tls_version = line.split(' ')[3]
if packet_number in d:
d[packet_number].append(tls_version)
else:
d[packet_number] = [tls_version]
print(d)
>>> {0: ['1.3', '1.2'], 1: ['1.3'], 2: ['1.3', '1.2'], 3: ['1.3'], 4: ['1.3', '1.2'], 5: ['1.3']}
import re
s = "57-09-71 МегаФонe-mail: ? vy:juf , h 5555y676hr965 silava.a@ttgr : https://loads.ru"
url_pattern = r'https?://\S+'
url_match = re.search(url_pattern, s)
if url_match:
url = url_match.group(0)
print(url)
else:
print("Ссылка не найдена")
>>> https://loads.ru
print(s.split(' ')[-1])
start_time
заведомо "меньше", чем server_time
, а вы вычитаете из меньшего большее, то и возникает разница в -1 день. abs
при подсчёте дельты:from datetime import datetime, timezone
start_time = datetime(2025, 1, 27, 23, 59, 59, tzinfo=timezone.utc)
server_time = datetime(2025, 1, 28, 0, 0, 0, tzinfo=timezone.utc)
delta = start_time - server_time
print("Дельта:", delta)
>>> Дельта: -1 day, 23:59:59
abs_delta = abs(start_time - server_time)
print("Дельта:", abs_delta)
>>> Дельта: 0:00:01
SORT_BUTTON = (By.XPATH, "(//span[@class='select2-selection select2-selection--single select2-selection--buttoned select2-selection--buttoned-dark select select--sorting'])[1]")
SORT_ASC_OPTION = (By.ID, 'select2-catalog_sorting_mobile-7h-result-jsvp-price:asc')
SORT_DESC_OPTION = (By.ID, 'select2-catalog_sorting_mobile-7h-result-jsvp-price:desc')
def select_sort_option()
добавил небольшую задержку (2-3 секунды) после WebDriverWait(self.driver, 10).until(EC.staleness_of(option))
. [...11900, 11900, 7735, 11900...],
что никак не будет равно отсортированному списку цен в assert
.test_sort_by_price[\u0426\u0435\u043d\u0430 \u043f\u043e \u0432\u043e\u0437\
,[pytest]
disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True
import requests
from bs4 import BeautifulSoup
def parse_table(div, results):
# Ищем таблицы внутри данного div
tables = div.find_all('table')
for table in tables:
rows = table.find_all('tr')
for row in rows:
cells = row.find_all('td')
if cells:
# Извлекаем название и ссылку
name = cells[0].get_text(strip=True)
link = cells[0].find('a')['href'] if cells[0].find('a') else None
if link:
results[name] = link
def recursive_parse(url, visited, results):
if url in visited:
return
visited.add(url)
print('Парсим URL:', url)
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# Ищем все div с itemscope
divs = soup.find_all('div', itemscope=True)
for div in divs:
parse_table(div, results) # Парсим таблицы внутри найденного div
# Ищем все ссылки на подстраницы
links = soup.find_all('a', href=True)
for link in links:
sub_url = link['href']
# Проверяем, что ссылка ведет на подстраницу и не является текущим URL
if 'respublika_bashkortostan' in sub_url and sub_url.startswith('http') and sub_url != url:
recursive_parse(sub_url, visited, results)
# Начальная URL
start_url = 'https://russiaschools.ru/respublika_bashkortostan/'
visited_urls = set()
results_dict = {}
recursive_parse(start_url, visited_urls, results_dict)
for name, link in results_dict.items():
print(f'Название: {name}, Ссылка: {link}')
import time
from numpy.random import randint, default_rng
def f(coords: list, time_movie: int, steps: int) -> list:
x_a, y_a = [], []
now = int(time.time() * 1000)
rng = default_rng()
timestamp = sorted(rng.integers(now, now + time_movie * 1000, size=(steps * len(coords) - 1) + 1))
for i in range(len(coords) - 1):
x1, y1, x2, y2 = coords[i] + coords[i + 1]
x_a += [x1] + sorted(randint(min(x1, x2), max(x1, x2), size=steps), reverse=1 if x1 > x2 else 0) + [x2]
y_a += [y1] + sorted(randint(min(y1, y2), max(y1, y2), size=steps), reverse=1 if x1 > x2 else 0) + [y2]
return [[x, y, t] for x, y, t in zip(x_a, y_a, timestamp)]
coords = [[392, 556], [95, 309], [207, 192]]
print(f(coords=coords, time_movie=2, steps=30))
import subprocess
# Функция для проверки доступности IP:port с помощью psping
def check_ip(ip_port):
try:
print(f"Проверяем доступность {ip_port}", end='')
# Выполняем команду psping
result = subprocess.run(['psping', ip_port], capture_output=True, text=True)
# Проверяем, есть ли в выводе сообщение об успешном пинге
if "(0% loss)" in result.stdout:
print(f"\rПроверяем доступность {ip_port} - доступен")
return True
if "(25% loss)" in result.stderr or "50% loss" in result.stdout:
print(f"\rПроверяем доступность {ip_port} - потери пакетов")
return True
if "(100% loss)" in result.stdout:
print(f"\rПроверяем доступность {ip_port} - недоступен")
return False
except Exception as e:
print(f"Ошибка при проверке {ip_port}: {e}")
return False
# Чтение IP:port из файла и запись доступных в другой файл
def check_ips_from_file(input_file, output_file):
with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
for line in infile:
ip_port = line.strip() # Убираем лишние пробелы и символы новой строки
if check_ip(ip_port):
outfile.write(ip_port + '\n') # Записываем доступный IP:port в файл
# Указываем имена файлов
input_file = 'ip.txt'
output_file = 'ipUP.txt'
# Запускаем проверку
check_ips_from_file(input_file, output_file)
import cv2
import numpy as np
def find_and_draw_template(template_path, original_image_path):
# Загрузка шаблона
template = cv2.imread(template_path)
template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
# Создание объекта ORB
orb = cv2.ORB_create()
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
# Обнаружение ключевых точек и вычисление дескрипторов для шаблона
keypoints_template, descriptors_template = orb.detectAndCompute(template_gray, None)
# Обработка изображения
image = original_image_path.copy()
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Обнаружение ключевых точек и вычисление дескрипторов для изображения
keypoints_image, descriptors_image = orb.detectAndCompute(image_gray, None)
# Сопоставление дескрипторов
matches = bf.match(descriptors_template, descriptors_image)
matches = sorted(matches, key=lambda x: x.distance)
# Отладочная информация
print(f"Общее количество найденных соответствий: {len(matches)}")
# Отбор лучших соответствий
good_matches = matches[:75]
print(f"Количество хороших соответствий: {len(good_matches)}")
# Проверка на наличие хороших соответствий
if len(good_matches) >= 4:
# Получение координат ключевых точек
src_pts = np.float32([keypoints_template[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints_image[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
# Нахождение матрицы гомографии
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
print("Гомография найдена.")
# Получение углов шаблона
h, w = template_gray.shape[:2]
pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
# Преобразование углов шаблона
dst = cv2.perspectiveTransform(pts, M)
# Обводим рамкой найденные области
image = cv2.polylines(image, [np.int32(dst)], isClosed=True, color=(0, 255, 0), thickness=3)
else:
print("Недостаточно хороших соответствий для нахождения гомографии.")
return image
# Пример использования функции
template_file = 'LED.jpg' # Шаблон
original_image_file = 'outputImage.jpg' # Исходное изображение
# Загрузка и обработка изображения
original_image = cv2.imread(original_image_file)
result_image = find_and_draw_template(template_file, original_image)
# Масштабируем изображение для отображения - не обязательно, у меня не вмещалось в просмотр
scale_percent = 50 # Процент уменьшения размера
width = int(result_image.shape[1] * scale_percent / 100)
height = int(result_image.shape[0] * scale_percent / 100)
resized_image = cv2.resize(result_image, (width, height), interpolation=cv2.INTER_AREA)
# Отображение результата
cv2.imshow('Detected Templates', resized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class ClockWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
# Устанавливаем параметры окна
self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
# Устанавливаем таймер для обновления времени
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.update_time)
self.timer.start(1000) # Обновляем каждую секунду
# Создаем метку для отображения времени
self.label = QtWidgets.QLabel(self)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setStyleSheet("font-size: 48px;") # Размер шрифта
# Устанавливаем начальное время
self.update_time()
# Устанавливаем размер окна
self.resize(200, 60)
# Переменные для перемещения окна
self.dragging = False
self.drag_position = None
def update_time(self):
current_time = QtCore.QTime.currentTime()
self.label.setText(current_time.toString("HH:mm:ss"))
self.check_color_below_widget()
def check_color_below_widget(self):
# Получаем глобальные координаты нижней границы виджета
global_pos = self.mapToGlobal(self.rect().bottomLeft())
# Определяем координаты точки на 10 пикселей ниже
point_below = global_pos + QtCore.QPoint(0, 10)
# Получаем цвет пикселя в этой точке
screen = QtWidgets.QApplication.primaryScreen()
pixel_color = screen.grabWindow(0).toImage().pixel(point_below.x(), point_below.y())
color = QtGui.QColor(pixel_color)
# Выводим значения RGB для отладки
print(f"Color below widget: R={color.red()}, G={color.green()}, B={color.blue()}")
# Вычисляем яркость цвета
brightness = (color.red() * 299 + color.green() * 587 + color.blue() * 114) / 1000
# Устанавливаем цвет текста в зависимости от яркости
if brightness < 128: # Темный фон
self.label.setStyleSheet("color: white; font-size: 48px;")
else: # Светлый фон
self.label.setStyleSheet("color: black; font-size: 48px;")
def paintEvent(self, event):
# Рисуем прозрачный фон
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setBrush(QtGui.QColor(0, 0, 0, 0))
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.dragging = True
self.drag_position = event.globalPos() - self.frameGeometry().topLeft()
def mouseMoveEvent(self, event):
if self.dragging:
self.move(event.globalPos() - self.drag_position)
def mouseReleaseEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.dragging = False
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
clock = ClockWidget()
clock.show()
sys.exit(app.exec_())
import pdfkit
import requests
options = {
"orientation": "portrait",
"page-size": "A4",
"margin-top": "1.0cm",
"margin-right": "1cm",
"margin-bottom": "1.5cm",
"margin-left": "1cm",
"encoding": "utf-8",
'footer-center': "Страница [page] из [toPage]",
'footer-font-size': 10,
}
url = 'https://pingvinus.ru/note/find-big-files'
r = requests.get(url)
pdfkit.from_string(r.text, f'{url.split("/")[-1]}.pdf', options=options, verbose=True)
out
.