from multiprocessing import Process
...
if __name__ == '__main__':
while True:
processes = []
processes.append(Process(target=main, args=('https://rust.tm/item/5358808098-0-Shipping%20Container%20Garage%20Door/', 'Shipping Container Garage Door', 60)))
processes.append(Process(target=main, args=('https://rust.tm/item/5518269987-0-Abyss%20Vest/', 'Abyss Vest', 140)))
processes.append(Process(target=main, args=('https://rust.tm/item/4136069987-0-Weather%20Large%20Wood%20Box/', 'Weather Large Wood Box', 100)))
for process in processes:
process.start()
for process in processes:
process.join()
time.sleep(5) # Задержка перед следующим циклом
with_extra_data=True
в свою самописную функцию, а в parser.get_flats()
- нет. Соответственно он и не парсит дополнительные поля, отсюда и: "пробовала вывести ключи: смотрю, а их там тупо нет". data = parser.get_flats(deal_type=deal_type, rooms=rooms, with_extra_data=True, additional_settings={"start_page": page, "end_page": page})
<span>
c текстом "Тип жилья", а именно такой селектор использовался в библиотеке парсера, следовательно он всегда будет отдавать -1
для object_type.__parse_flat_offer_page_json__(self)
после инициализации словаря page_data
, добавить: ot = self.offer_page_soup.select_one('[data-name="OfferSummaryInfoItem"] p:nth-of-type(2)').get_text()
page_data["object_type"] = ot
# if "Тип жилья" == span.text:
# page_data["object_type"] = spans[index + 1].text
import wx
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.SetSize((250, 250))
self.SetTitle("frame")
sizer_1 = wx.WrapSizer(wx.VERTICAL)
fields = [
("Ширина (м)", "a"),
("Длина (м)", "b"),
("Высота (м)", "h"),
("Окно ширина (м)", "o1"),
("Окно высота (м)", "o2"),
("Дверь ширина (м)", "d1"),
("Дверь высота (м)", "d2"),
]
# Create grid sizers and controls dynamically
for label_text, attr in fields:
grid_sizer = wx.GridSizer(1, 2, 0, 0)
sizer_1.Add(grid_sizer, 1, wx.EXPAND, 0)
label = wx.StaticText(self, wx.ID_ANY, label_text)
grid_sizer.Add(label, 0, wx.ALL, 1)
text_ctrl = wx.TextCtrl(self, wx.ID_ANY, "")
setattr(self, attr, text_ctrl) # Store the text control in the instance
grid_sizer.Add(text_ctrl, 0, 0, 0)
# Create a horizontal sizer for the result and button
h_sizer = wx.BoxSizer(wx.HORIZONTAL)
# Result text control
self.itogo = wx.TextCtrl(self, wx.ID_ANY, "")
self.itogo.SetBackgroundColour((171, 171, 171))
h_sizer.Add(self.itogo, 1, wx.EXPAND | wx.ALL, 5)
# Calculate button
self.button_1 = wx.Button(self, wx.ID_ANY, "Посчитать", size=(110, 21))
h_sizer.Add(self.button_1, 0, wx.ALL, 5)
self.button_1.Bind(wx.EVT_BUTTON, self.onclick)
# Add the horizontal sizer to the main sizer
sizer_1.Add(h_sizer, 0, wx.EXPAND, 0)
self.SetSizer(sizer_1)
self.Layout()
def onclick(self, event):
a = float(self.a.GetValue())
b = float(self.b.GetValue())
h = float(self.h.GetValue())
o1 = float(self.o1.GetValue())
o2 = float(self.o2.GetValue())
d1 = float(self.d1.GetValue())
d2 = float(self.d2.GetValue())
result = round(a * 2 * h + b * 2 * h - o1 * o2 - d1 * d2, 2)
self.itogo.SetValue(str(result))
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(None, wx.ID_ANY, "")
self.SetTopWindow(self.frame)
self.frame.Show()
return True
if __name__ == "__main__":
app = MyApp(0)
app.MainLoop()
r
перед ф-строкой во избежание нескольких invalid escape sequence:command = rf'C:\PsTools\psexec.exe -i 1 -s \\192.168.11.18 -u user -p password calc.exe'
import subprocess
def f():
command = rf'C:\Portable\Sysinternal\PsExec.exe -i 1 -s \\192.168.0.3 -u user -p password calc.exe'
return subprocess.call(command, stdout=subprocess.DEVNULL)
interactive=True
, надо указать номер сессии (можно узнать через cmd -> query user
), например: interactive_session=1
. Это аналог -i 1
в psexec.c.run_executable (executable: "cmd.exe", arguments=r"/c start calc.exe", interactive=True, interactive_session=1)
num_1 = None
num_2 = None
effect = None
while True:
if num_1 is None:
input_value = input("Введите первое число: ")
if input_value.isdigit():
num_1 = int(input_value)
else:
print('Вы ввели не число!')
continue
if num_2 is None:
input_value = input("Введите второе число: ")
if input_value.isdigit():
num_2 = int(input_value)
else:
print('Вы ввели не число!')
continue
if effect is None:
input_value = input(
"Напишите что вы хотите сделать (отнять, прибавить, умножить, разделить, возвести в степень, целое деление, остаток от деления): ")
if input_value in ("+", "-", "*", "/", "**", "//", "%"):
effect = input_value
break
else:
print('Нету такого действия!')
continue
# Выполнение операции
if effect == "+":
print(num_1 + num_2)
elif effect == "-":
print(num_1 - num_2)
elif effect == "*":
print(num_1 * num_2)
elif effect == "/":
print(num_1 / num_2)
elif effect == "**":
print(num_1 ** num_2)
elif effect == "//":
print(num_1 // num_2)
elif effect == "%":
print(num_1 % num_2)
l = []
for i in range(3):
l.append(lambda: i)
print([f() for f in l])
>>> [2, 2, 2]
l = []
for i in range(3):
l.append(lambda i = i : i)
print([f() for f in l])
>>> [0, 1, 2]
while True:
try:
x = pa.locateCenterOnScreen(r"C:\Python Scripts\library\proga.png", confidence=0.5)
print(x)
except Exception as e:
print(e)
len_pass_numbers.lower()
(и прочие) возвращает вам строку 'да', а вы сравниваете с 'Да'. chars
- пустой.from string import digits, ascii_lowercase, ascii_uppercase, punctuation
import requests
url = 'https://texttospeech.ru/api/v1/login'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0',
'Content-Type': 'text/plain;charset=UTF-8',
}
data = {"email": "sample@email.com", "pass": "password", "captcha": ""}
session = requests.Session()
response = session.post(url, json=data)
print(response.text)
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0',
'Content-Type': 'text/plain;charset=UTF-8',
}
def get_token() -> str:
url = 'https://texttospeech.ru/api/v1/login'
data = {"email": "sample@email.com", "pass": "password", "captcha": ""}
with requests.Session() as session:
response = session.post(url, headers=headers, json=data)
token = response.json().get('data').get('token')
return token
headers['token'] = get_token()
def synthesize(text: str) -> None:
url = 'https://texttospeech.ru/api/v1/synthesize'
data = {"rate": "0", "pitch": "0", "volume": "0", "hertz": "0", "shift": "0", "echo": "0",
"text": f'{text}',
"code": "ru-RU009",
"format": "mp3"}
with requests.Session() as session:
response = session.post(url, headers=headers, json=data)
if response.status_code == 200:
print(response.json().get('message'))
filelink = response.json().get('data').get('filelink')
with open(f'{text[0:10]}.mp3', 'wb') as file:
response = session.get(f'https://texttospeech.ru/{filelink}', headers=headers)
file.write(response.content)
else:
print(response.text)
synthesize('Привет мир')
on_component
- это не атрибут бота, а внутреннее событие.# Обработчик нажатия на кнопку присоединения к игре
@bot.event
async def on_component(interaction):
global players
if interaction.author not in players:
players[interaction.author] = None
await interaction.response.send_message(content=f"{interaction.author.mention} присоединился к игре!",
ephemeral=True)
else:
await interaction.response.send_message(content="Вы уже присоединились к игре!", ephemeral=True)
intents = disnake.Intents.all()
from requests_html import HTMLSession
def download(url):
session = HTMLSession()
resp = session.get(url)
resp.html.render()
if resp.status_code == 200:
list_of_img = resp.html.find('img')
d = list_of_img[0].attrs
image_url = d['srcset'].split(',')[-1].split(' ')[0]
image_name = image_url.split('/')[-1]
image = session.get(image_url).content
with open(image_name, 'wb') as file:
file.write(image)
else:
print(f"[ERROR] Не удалось загрузить изображение:\n{url}")
session.close()
download('https://scrolller.com/i-dragged-my-brother-out-at-1am-to-see-the-aogsmn8ihx')
...
text = '''Номер телефону: `+1111111`
Сайт: auto-repair-shop-10715.business.site
Робочий час: Понеділок - Субота / 08:00 - 18:00'''
bot.edit_message_text(chat_id=call.message.chat.id,
message_id=call.message.id,
text=text,
reply_markup=ans, parse_mode='MARKDOWN')
...
provider=g4f.Provider.You
, смотреть активные провайдеры здесь.import g4f
response = g4f.ChatCompletion.create(
model=g4f.models.gpt_4,
messages=[{"role": "user", "content": "Hello"}],
provider=g4f.Provider.You,
stream=True,
)
for message in response:
print(message, flush=True, end="")
from g4f.client import Client
client = Client(
api_key="...",
...
)