from multiprocessing import Lock, Pool
lock = Lock()
with lock:
driver = uc.Chrome(seleniumwire_options=wire_options, options=options)
from multiprocessing import Manager, Pool
manager = Manager()
def get_whoer(proxy: str):
# ...
if __name__ == '__main__':
"""ip:port:login:password"""
with Pool(processes=2) as p:
p.map(get_whoer, proxy_list)
from queue import Queue
from multiprocessing import Pool
queue = Queue()
def get_whoer(proxy: str):
# ...
if __name__ == '__main__':
"""ip:port:login:password"""
proxy_list = list(map(str.rstrip, open('proxy.txt').readlines()))
for proxy in proxy_list:
queue.put(proxy)
with Pool(processes=2) as p:
p.map(get_whoer, range(len(proxy_list)))
Есть ли возможность в python прописать длинный многоуровневый список со словарями и вставлять туда переменные чтобы по итогу я мог сгенерировать из него JSON?
import json
krevetko = 'иа креветкО!'
data = {
"form_id": 1345,
"fields": [
{"id": 1, "value": krevetko}, # <-- this is, krevetko variable
{"id": 2, "value": 10306.25},
{"id": 3, "value": {"item_id": 845}},
{
"id": 4,
"value": [
{
"row_id": 0,
"cells": [
{"id": 6, "value": "2017-08-26"},
{"id": 9, "value": 10000}
]
}
]
}
]
}
print(json.dumps(data))
# {"form_id": 1345, "fields": [{"id": 1, "value": "\u0438\u0430 \u043a\u0440\u0435\u0432\u0435\u0442\u043a\u041e!"}, {"id": 2, "value": 10306.25}, {"id": 3, "value": {"item_id": 845}}, {"id": 4, "value": [{"row_id": 0, "cells": [{"id": 6, "value": "2017-08-26"}, {"id": 9, "value": 10000}]}]}]}
import json
data_dict = {"name": "John", "age": 30}
data_list = [1, 2, 3, 4]
data_string = "Hello, world!"
data_string_cyrillic = "иа креветкО!"
data_number = 42
data_boolean = True
data_none = None
print(json.dumps(data_dict)) # {"name": "John", "age": 30}
print(json.dumps(data_list)) # [1, 2, 3, 4]
print(json.dumps(data_string)) # "Hello, world!"
print(json.dumps(data_string_cyrillic)) # "\u0438\u0430 \u043a\u0440\u0435\u0432\u0435\u0442\u043a\u041e!"
print(json.dumps(data_number)) # 42
print(json.dumps(data_boolean)) # true
print(json.dumps(data_none)) # null
Существует ли способ имитировать эти действия так, чтобы JavaScript успешно их распознавал
Существует ли способ имитировать эти действия так, чтобы JavaScript успешно их распознавал, но без использования библиотеки PyAutoGUI или аналогичных, которые контролируют реальный курсор?
Пример файла JSON
Например мне нужно найти список с id 10 и сохранить все его элементы в отдельный
list_data = [
{
"id": 121,
"type": "form_link",
"name": "cust",
"tooltip": "",
"value": {
"task_id": 432122,
"task_ids": [
1236733
],
"subject": "test_event"
}
},
{
"id": 122,
"type": "text",
"name": "Регион",
"tooltip": "",
"value": "MGN."
},
{
"id": 129,
"type": "text",
"name": "Проблема",
"tooltip": "Заправьте картридж",
"value": "TEST"
},
{
"id": 10,
"type": "person",
"name": "Ответственный",
"tooltip": "none",
"value": {
"id": 888,
"first_name": "Pavel",
"last_name": "Perkov",
"email": "example@anime.com",
"type": "user",
"status": "WORKING",
"web_session_settings": {
"disable": False
},
"mobile_session_settings": {
"disable": False
}
}
}
]
# mega function
def test(data, target_id):
for item in data:
if item.get('id') == target_id:
return item
return None
res = test(list_data, 10)
print(res)
# {'id': 10, 'type': 'person', 'name': 'Ответственный', 'tooltip': 'none', 'value': {'id': 888, 'first_name': 'Pavel', 'last_name': 'Perkov', 'email': 'example@anime.com', 'type': 'user', 'status': 'WORKING', 'web_session_settings': {'disable': False}, 'mobile_session_settings': {'disable': False}}}
item2 = types.KeyboardButton(text="Семья в России"),
bot.reply_to
это откуда? По идее, должно быть bot.send_message
, исправил код, допишите все нужные кнопки и попробуйте, должно заработать:@bot.message_handler(commands=["start"])
def start(message):
keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
item1 = types.KeyboardButton(text="Основные документы гражданина Российской Федерации")
# прочее...
keyboard.add(item1, item2)
# прочее...
bot.send_message(
message.chat.id,
f"Привет",
f"{message.from_user.first_name}! Я бот, который поможет тебе. Что ты хочешь узнать..?",
reply_markup=keyboard)
Вот сама ошибка(походу что-то я сделал не так и огроомная ошибка поменялась в маленькую):
C:\Users\akrav\Desktop\машынки\main.py:183: RuntimeWarning: coroutine 'get_cards' was never awaited
get_cards(message)
# def new_card(message: types.Message):
# get_cards(message)
async def card_handler(message: types.Message):
await get_cards(message)
x: None
, тогда можно будет вызывать функцию без аргументов:from typing import overload, Union
@overload
def Func(a: int) -> int: ...
@overload
def Func(a: bool) -> bool: ...
@overload
def Func() -> None: ...
def Func(x: Union[int, bool, None] = None) -> Union[int, bool, None]:
if x is None:
return None
elif isinstance(x, bool):
return x
elif isinstance(x, int):
return 333
else:
raise ValueError("Invalid argument type.")
print(Func(10)); # 333
print(Func(True)); # True
print(Func()); # None
print(Func('kek')); # ValueError: Invalid argument type.
import json
def on_message(ws, message):
data = json.loads(message)
s = data.get("s")
p = data.get("p")
if p:
_p = float(p)
if _p > 51500:
print(f"Монета {s} больше 51500, текущая цена: {_p}")
else:
print(f"Монета {s} меньше или равна 51500, текущая цена: {_p}")
def sort_pair(a, b):
def sort_pair(pair):
a, b = pair
if a <= b:
return (a, b)
else:
return (b, a)
print(sort_pair((5, 1))) # (1, 5)
print(sort_pair((2, 2))) # (2, 2)
print(sort_pair((7, 8))) # (7, 8)
from typing import Tuple
def sort_pair(pair: Tuple[int, int]) -> Tuple[int, int]:
a, b = pair
if a <= b:
return (a, b)
else:
return (b, a)
print(sort_pair((5, 1))) # (1, 5)
print(sort_pair((2, 2))) # (2, 2)
print(sort_pair((7, 8))) # (7, 8)
Message: move target out of bounds: viewport size: 452, 362 (Session info: MicrosoftEdge=121.0.2277.128).
move_by_offset
viewport size: 452, 362
Может ли на hh.ru стоять какая-то защита от парсинга?)
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
}
res = requests.get('https://tomsk.hh.ru/article/31475', headers=headers)
if res.status_code == 200:
soup = BeautifulSoup(res.text, 'html.parser')
el = soup.find('div', class_='URS-ratingTable')
if el:
print(el)
else:
print('Table not found!')
else:
print('The problem with connecting to the website', {res.status_code})
def play(file_path):
pygame.mixer.init()
pygame.mixer.music.load(file_path)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy(): # if True, the melody is being played
time.sleep(1)
play('path_to_file/file.ogg') # dancing dancing dancing...
async function getValue() {
const input = document.querySelector('#input-id');
try {
const res = await fetch('/', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({'value': input.value})
});
if (res.ok) {
console.log('Send success!');
} else {
throw new Error(`Send error, ${res.statusText}`);
}
} catch (error) {
console.error('Error', error);
}
}
from flask import Flask, render_template, request, jsonify
import json
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html')
elif request.method == 'POST':
try:
data = request.json
if 'value' in data:
value = validate(data['value'])
return jsonify({'message': 'Success!', 'value': value}), 200
else:
raise KeyError('Value key not found')
except (KeyError, json.JSONDecodeError) as e:
return jsonify({'error': 'Invalid data format'}), 400
def validate(value):
return value
if __name__ == '__main__':
app.run(debug=True)
что стоит учить, чтобы стать действительно хорошим специалистом в бэкенд разработке