Уведомления

Группа в Telegram: @pythonsu

Уведомления

  • Found 3492 posts.

Python для новичков » Помогите пожалуйста с написанием кода, очень нужно) » Авг. 26, 2022 11:53:02

Ребят, привет! Написал смс бомбер, в коде приделал его к телеботу, чтобы он работал, после определенных сообщений, залил на хостинг, но тут выявил проблемку! Когда в чат боте тг одновременно задают просьбу о спаме ( т.е. скидывают свои телефоны) сообщения идут только на номер, который был отправлен первый! А если кто-то третий попробует в это же время написать чат боту номер жертвы, то он вовсе перестает отвечать) Помогите пожалуйста в чем проблема? Так как переменная одна, скорее всего надо какие то массивы или что? Буду рад если поможете) Спасибо!
Просто руки уже повесил)

Центр помощи » Помогите решить задачи » Авг. 24, 2022 16:41:33

У меня есть таблица оскаров, в которой указаны год, возраст,имя и две колонки с фильмами. Мне нужно с помощью pandas вывести строки с теми актерами у которых в обоих столбцах фильмы, написаны названия фильмов , а не None.
Еще нужно вывести актеров, которые старше 30 лет, я попробовал, не получилось:
import pandas as pd
df = pd.read_csv('/content/oscar_age_female (1).csv')
above_30 = df[df > 30]
above_30.head()
df.head()

KeyError Traceback (most recent call last)

/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3360 try:
-> 3361 return self._engine.get_loc(casted_key)
3362 except KeyError as err:


4 frames
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()


KeyError: ‘Age’


The above exception was the direct cause of the following exception:


KeyError Traceback (most recent call last)

/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3361 return self._engine.get_loc(casted_key)
3362 except KeyError as err:
-> 3363 raise KeyError(key) from err
3364
3365 if is_scalar(key) and isna(key) and not self.hasnans:


KeyError: ‘Age’

Как мне эти две задачи сделать?

Python проекты » Как сделать выгрузку фото по дате? Python/telethon » Авг. 16, 2022 10:18:00

Всем привет. Делаю бота, который выгружает фото с телеграмм-каналов на сервер. Каналы каждый день добавляют новые фото и мне нужно сделать ежедневную выгрузку за вчерашний день. В документации Telethon нашел min_date, max_datе, но при попытке применить получаю ошибку. Что добавить, чтобы фотки выгружались только за вчерашний день?

for title in sh_lst:
for chat in result.chats:


if chat.title == title:
messages = client.get_messages(chat, limit=300, filter=InputMessagesFilterPhotos)

for message in tqdm(messages):
message.download_media('../photo/' + title + ‘/’)

Python для новичков » QtextEdit и отступы первых строк абзаца » Авг. 13, 2022 05:37:36

Добрый день. Необходимо, чтобы QtextEdit текст был отформатирован с абзацным отступом первой строки по умолчанию, как в WORD (см.рисунок). Как такое сделать?

Network » Парсинг сайта » Июль 30, 2022 11:25:11

Добрый день.
Нужно пропарсить страницу https://catalog.onliner.by/headphones/apple/mlwk3rua для нахождения минимальной и максимальной цены.

Проблема в том, что когда я открываю в браузере я вижу справа список цен и соответственно могу через F12 найти нужные данные по селектору.
Но когда я делаю
 url_path = 'https://catalog.onliner.by/headphones/apple/mlwk3rua'
response = requests.get(url_path)
f = open('rez.html', 'w',encoding="utf-8")
f.write(response.text)
f.close()
В полученном ответе нет правой панели с ценами

Можно в 2 словах объяснить почему и что можно сделать?

Python для экспертов » Сборка интерпретатора Python 3.10.5 из исходников в Linux » Июль 27, 2022 18:15:39

Всем привет!

В общем ситуация такая: У меня есть старенький ноутбук, в котором уже даже нет жёсткого диска, и который я использую чисто для запуска Linux в режиме Live USB, - да, мне этого вполне достаточно И вот решил я так сказать, немного поиграться с питоном

В данный момент я использую Linux Mint (LMDE 5), где установлен Python 3.9.2. Решил поставить самую последнюю на данный момент версию Python 3.10.5. Решил собрать из исходников. Скачал исходники с официального сайта, распаковал архив, почитал README, в итоге cделал так:

Сперва активировал source code repositories (чтобы установить зависимости). Затем:

 sudo apt update
sudo apt build-dep python3
sudo apt install pkg-config
sudo apt install build-essential gdb lcov pkg-config \
      libbz2-dev libffi-dev libgdbm-dev libgdbm-compat-dev liblzma-dev \
      libncurses5-dev libreadline6-dev libsqlite3-dev libssl-dev \
      lzma lzma-dev tk-dev uuid-dev zlib1g-dev
cd Downloads/Python-3.10.5/
sudo ./configure --enable-optimizations --with-lto
sudo make altinstall
sudo make test

При прохождении тестов получил следующее:

  CC='gcc -pthread' LDSHARED='gcc -pthread -shared   -fno-semantic-interposition -flto -fuse-linker-plugin -ffat-lto-objects -flto-partition=none -g ' OPT='-DNDEBUG -g -fwrapv -O3 -Wall' 	_TCLTK_INCLUDES='-I/usr/include/tcl8.6' _TCLTK_LIBS='-ltk8.6 -ltkstub8.6 -ltcl8.6 -ltclstub8.6' 	./python -E ./setup.py  build
running build
running build_ext
The following modules found by detect_modules() in setup.py, have been
built by the Makefile instead, as configured by the Setup files:
_abc                  pwd                   time               
running build_scripts
copying and adjusting /home/mint/Downloads/Python-3.10.5/Tools/scripts/pydoc3 -> build/scripts-3.10
copying and adjusting /home/mint/Downloads/Python-3.10.5/Tools/scripts/idle3 -> build/scripts-3.10
copying and adjusting /home/mint/Downloads/Python-3.10.5/Tools/scripts/2to3 -> build/scripts-3.10
changing mode of build/scripts-3.10/pydoc3 from 644 to 755
changing mode of build/scripts-3.10/idle3 from 644 to 755
changing mode of build/scripts-3.10/2to3 from 644 to 755
renaming build/scripts-3.10/pydoc3 to build/scripts-3.10/pydoc3.10
renaming build/scripts-3.10/idle3 to build/scripts-3.10/idle3.10
renaming build/scripts-3.10/2to3 to build/scripts-3.10/2to3-3.10
./python  ./Tools/scripts/run_tests.py -v test_os
== CPython 3.10.5 (main, Jul 27 2022, 19:31:59) [GCC 10.2.1 20210110]
== Linux-5.10.0-12-amd64-x86_64-with-glibc2.31 little-endian
== cwd: /home/mint/Downloads/Python-3.10.5/build/test_python_60256æ
== CPU count: 2
== encodings: locale=UTF-8, FS=utf-8
Using random seed 881896
0:00:00 load avg: 0.69 Run tests in parallel using 4 child processes
0:00:03 load avg: 0.71 [1/1/1] test_os failed (1 failure)
test_blocking (test.test_os.BlockingTests) ... ok
test_compare_to_walk (test.test_os.BytesFwalkTests) ... ok
test_dir_fd (test.test_os.BytesFwalkTests) ... ok
test_fd_leak (test.test_os.BytesFwalkTests) ... ok
test_file_like_path (test.test_os.BytesFwalkTests) ... ok
test_walk_bad_dir (test.test_os.BytesFwalkTests) ... ok
test_walk_bottom_up (test.test_os.BytesFwalkTests) ... ok
test_walk_prune (test.test_os.BytesFwalkTests) ... ok
test_walk_symlink (test.test_os.BytesFwalkTests) ... ok
test_walk_topdown (test.test_os.BytesFwalkTests) ... ok
test_yields_correct_dir_fd (test.test_os.BytesFwalkTests) ... ok
test_file_like_path (test.test_os.BytesWalkTests) ... ok
test_walk_bad_dir (test.test_os.BytesWalkTests) ... ok
test_walk_bottom_up (test.test_os.BytesWalkTests) ... ok
test_walk_many_open_files (test.test_os.BytesWalkTests) ... ok
test_walk_prune (test.test_os.BytesWalkTests) ... ok
test_walk_symlink (test.test_os.BytesWalkTests) ... ok
test_walk_topdown (test.test_os.BytesWalkTests) ... ok
test_cpu_count (test.test_os.CPUCountTests) ... ok
test_chown_gid (test.test_os.ChownFileTests) ... skipped 'test needs at least 2 groups'
test_chown_uid_gid_arguments_must_be_index (test.test_os.ChownFileTests) ... ok
test_chown_with_root (test.test_os.ChownFileTests) ... ok
test_chown_without_permission (test.test_os.ChownFileTests) ... skipped 'test needs non-root account and more than one user'
test_devnull (test.test_os.DevNullTests) ... ok
test_bad_fd (test.test_os.DeviceEncodingTests) ... ok
test_device_encoding (test.test_os.DeviceEncodingTests) ... ok
test___repr__ (test.test_os.EnvironTests)
Check that the repr() of os.environ looks like environ({...}). ... ok
test_bool (test.test_os.EnvironTests) ... ok
test_constructor (test.test_os.EnvironTests) ... ok
test_environb (test.test_os.EnvironTests) ... ok
test_get (test.test_os.EnvironTests) ... ok
test_get_exec_path (test.test_os.EnvironTests) ... ok
test_getitem (test.test_os.EnvironTests) ... ok
test_ior_operator (test.test_os.EnvironTests) ... ok
test_ior_operator_invalid_dicts (test.test_os.EnvironTests) ... ok
test_ior_operator_key_value_iterable (test.test_os.EnvironTests) ... ok
test_items (test.test_os.EnvironTests) ... ok
test_iter_error_when_changing_os_environ (test.test_os.EnvironTests) ... ok
test_iter_error_when_changing_os_environ_items (test.test_os.EnvironTests) ... ok
test_iter_error_when_changing_os_environ_values (test.test_os.EnvironTests) ... ok
test_key_type (test.test_os.EnvironTests) ... ok
test_keys (test.test_os.EnvironTests) ... ok
test_keyvalue_types (test.test_os.EnvironTests) ... ok
test_len (test.test_os.EnvironTests) ... ok
test_or_operator (test.test_os.EnvironTests) ... ok
test_os_popen_iter (test.test_os.EnvironTests) ... ok
test_pop (test.test_os.EnvironTests) ... ok
test_popitem (test.test_os.EnvironTests) ... ok
test_putenv_unsetenv (test.test_os.EnvironTests) ... ok
test_putenv_unsetenv_error (test.test_os.EnvironTests) ... ok
test_read (test.test_os.EnvironTests) ... ok
test_ror_operator (test.test_os.EnvironTests) ... ok
test_setdefault (test.test_os.EnvironTests) ... ok
test_update (test.test_os.EnvironTests) ... ok
test_update2 (test.test_os.EnvironTests) ... ok
test_values (test.test_os.EnvironTests) ... ok
test_write (test.test_os.EnvironTests) ... ok
test_eventfd_initval (test.test_os.EventfdTests) ... ok
test_eventfd_select (test.test_os.EventfdTests) ... ok
test_eventfd_semaphore (test.test_os.EventfdTests) ... ok
test_execv_with_bad_arglist (test.test_os.ExecTests) ... ok
test_execve_invalid_env (test.test_os.ExecTests) ... ok
test_execve_with_empty_path (test.test_os.ExecTests) ... skipped 'Win32-specific test'
test_execvpe_with_bad_arglist (test.test_os.ExecTests) ... ok
test_execvpe_with_bad_program (test.test_os.ExecTests) ... ok
test_internal_execvpe_str (test.test_os.ExecTests) ... ok
test_os_all (test.test_os.ExportsTests) ... ok
test_fds (test.test_os.ExtendedAttributeTests) ... skipped 'no non-broken extended attribute support'
test_lpath (test.test_os.ExtendedAttributeTests) ... skipped 'no non-broken extended attribute support'
test_simple (test.test_os.ExtendedAttributeTests) ... skipped 'no non-broken extended attribute support'
test_dup (test.test_os.FDInheritanceTests) ... ok
test_dup2 (test.test_os.FDInheritanceTests) ... ok
test_dup_nul (test.test_os.FDInheritanceTests) ... skipped 'win32-specific test'
test_dup_standard_stream (test.test_os.FDInheritanceTests) ... ok
test_get_inheritable_cloexec (test.test_os.FDInheritanceTests) ... ok
test_get_set_inheritable (test.test_os.FDInheritanceTests) ... ok
test_get_set_inheritable_badf (test.test_os.FDInheritanceTests) ... ok
test_get_set_inheritable_o_path (test.test_os.FDInheritanceTests) ... ok
test_open (test.test_os.FDInheritanceTests) ... ok
test_openpty (test.test_os.FDInheritanceTests) ... ok
test_pipe (test.test_os.FDInheritanceTests) ... ok
test_set_inheritable_cloexec (test.test_os.FDInheritanceTests) ... ok
test_identity (test.test_os.FSEncodingTests) ... ok
test_nop (test.test_os.FSEncodingTests) ... ok
test_access (test.test_os.FileTests) ... ok
test_closerange (test.test_os.FileTests) ... ok
test_copy_file_range (test.test_os.FileTests) ... ok
test_copy_file_range_invalid_values (test.test_os.FileTests) ... ok
test_copy_file_range_offset (test.test_os.FileTests) ... ok
test_fdopen (test.test_os.FileTests) ... ok
test_large_read (test.test_os.FileTests) ... skipped 'not enough memory: 2.0G minimum needed'
test_open_keywords (test.test_os.FileTests) ... ok
test_read (test.test_os.FileTests) ... ok
test_rename (test.test_os.FileTests) ... ok
test_replace (test.test_os.FileTests) ... ok
test_splice (test.test_os.FileTests) ... ok
test_splice_invalid_values (test.test_os.FileTests) ... ok
test_splice_offset_in (test.test_os.FileTests) ... ok
test_splice_offset_out (test.test_os.FileTests) ... ok
test_symlink_keywords (test.test_os.FileTests) ... ok
test_write (test.test_os.FileTests) ... ok
test_write_windows_console (test.test_os.FileTests) ... skipped 'test specific to the Windows console'
test_fork (test.test_os.ForkTests) ... ok
test_compare_to_walk (test.test_os.FwalkTests) ... ok
test_dir_fd (test.test_os.FwalkTests) ... ok
test_fd_leak (test.test_os.FwalkTests) ... ok
test_file_like_path (test.test_os.FwalkTests) ... ok
test_walk_bad_dir (test.test_os.FwalkTests) ... ok
test_walk_bottom_up (test.test_os.FwalkTests) ... ok
test_walk_prune (test.test_os.FwalkTests) ... ok
test_walk_symlink (test.test_os.FwalkTests) ... ok
test_walk_topdown (test.test_os.FwalkTests) ... ok
test_yields_correct_dir_fd (test.test_os.FwalkTests) ... ok
test_getrandom0 (test.test_os.GetRandomTests) ... ok
test_getrandom_nonblock (test.test_os.GetRandomTests) ... ok
test_getrandom_random (test.test_os.GetRandomTests) ... ok
test_getrandom_type (test.test_os.GetRandomTests) ... ok
test_getrandom_value (test.test_os.GetRandomTests) ... ok
test_link (test.test_os.LinkTests) ... ok
test_link_bytes (test.test_os.LinkTests) ... ok
test_unicode_name (test.test_os.LinkTests) ... ok
test_getlogin (test.test_os.LoginTests) ... skipped 'Skip due to platform/environment differences on *NIX buildbots'
test_exist_ok_existing_directory (test.test_os.MakedirTests) ... ok
test_exist_ok_existing_regular_file (test.test_os.MakedirTests) ... ok
test_exist_ok_s_isgid_directory (test.test_os.MakedirTests) ... ok
test_makedir (test.test_os.MakedirTests) ... ok
test_mode (test.test_os.MakedirTests) ... ok
test_memfd_create (test.test_os.MemfdCreateTests) ... ok
test_getcwd (test.test_os.MiscTests) ... ok
test_getcwd_long_path (test.test_os.MiscTests) ... Tested current directory length: 2000
ok
test_getcwdb (test.test_os.MiscTests) ... ok
test_directory_link_nonlocal (test.test_os.NonLocalSymlinkTests)
The symlink target should resolve relative to the link, not relative ... ok
test_oserror_filename (test.test_os.OSErrorTests) ... ok
test_path_t_converter (test.test_os.PathTConverterTests) ... ok
test_path_t_converter_and_custom_class (test.test_os.PathTConverterTests) ... ok
test_listdir (test.test_os.Pep383Tests) ... ok
test_open (test.test_os.Pep383Tests) ... ok
test_stat (test.test_os.Pep383Tests) ... ok
test_statvfs (test.test_os.Pep383Tests) ... ok
test_getppid (test.test_os.PidTests) ... ok
test_waitpid (test.test_os.PidTests) ... ok
test_waitpid_windows (test.test_os.PidTests) ... skipped 'win32-specific test'
test_waitstatus_to_exitcode (test.test_os.PidTests) ... ok
test_waitstatus_to_exitcode_kill (test.test_os.PidTests) ... ok
test_waitstatus_to_exitcode_windows (test.test_os.PidTests) ... skipped 'win32-specific test'
test_setegid (test.test_os.PosixUidGidTests) ... ok
test_seteuid (test.test_os.PosixUidGidTests) ... ok
test_setgid (test.test_os.PosixUidGidTests) ... ok
test_setregid (test.test_os.PosixUidGidTests) ... ok
test_setregid_neg1 (test.test_os.PosixUidGidTests) ... ok
test_setreuid (test.test_os.PosixUidGidTests) ... ok
test_setreuid_neg1 (test.test_os.PosixUidGidTests) ... ok
test_setuid (test.test_os.PosixUidGidTests) ... ok
test_set_get_priority (test.test_os.ProgramPriorityTests) ... ok
test_bytes (test.test_os.ReadlinkTests) ... ok
test_missing_link (test.test_os.ReadlinkTests) ... ok
test_not_symlink (test.test_os.ReadlinkTests) ... ok
test_pathlike (test.test_os.ReadlinkTests) ... ok
test_pathlike_bytes (test.test_os.ReadlinkTests) ... ok
test_remove_all (test.test_os.RemoveDirsTests) ... ok
test_remove_nothing (test.test_os.RemoveDirsTests) ... ok
test_remove_partial (test.test_os.RemoveDirsTests) ... ok
test_nowait (test.test_os.SpawnTests) ... ok
test_spawnl (test.test_os.SpawnTests) ... ok
test_spawnl_noargs (test.test_os.SpawnTests) ... ok
test_spawnle (test.test_os.SpawnTests) ... ok
test_spawnle_noargs (test.test_os.SpawnTests) ... ok
test_spawnlp (test.test_os.SpawnTests) ... ok
test_spawnlpe (test.test_os.SpawnTests) ... ok
test_spawnv (test.test_os.SpawnTests) ... ok
test_spawnv_noargs (test.test_os.SpawnTests) ... ok
test_spawnve (test.test_os.SpawnTests) ... ok
test_spawnve_bytes (test.test_os.SpawnTests) ... ok
test_spawnve_invalid_env (test.test_os.SpawnTests) ... ok
test_spawnve_noargs (test.test_os.SpawnTests) ... ok
test_spawnvp (test.test_os.SpawnTests) ... ok
test_spawnvpe (test.test_os.SpawnTests) ... ok
test_spawnvpe_invalid_env (test.test_os.SpawnTests) ... ok
test_15261 (test.test_os.StatAttributeTests) ... skipped 'Win32 specific tests'
test_1686475 (test.test_os.StatAttributeTests) ... skipped 'Win32 specific tests'
test_access_denied (test.test_os.StatAttributeTests) ... skipped 'Win32 specific tests'
test_file_attributes (test.test_os.StatAttributeTests) ... skipped 'st_file_attributes is Win32 specific'
test_stat_attributes (test.test_os.StatAttributeTests) ... ok
test_stat_attributes_bytes (test.test_os.StatAttributeTests) ... ok
test_stat_block_device (test.test_os.StatAttributeTests) ... skipped 'Win32 specific tests'
test_stat_result_pickle (test.test_os.StatAttributeTests) ... ok
test_statvfs_attributes (test.test_os.StatAttributeTests) ... ok
test_statvfs_result_pickle (test.test_os.StatAttributeTests) ... ok
test_does_not_crash (test.test_os.TermsizeTests)
Check if get_terminal_size() returns a meaningful value. ... skipped 'failed to query terminal size'
test_stty_match (test.test_os.TermsizeTests)
Check if stty returns the same results ... ok
test_uninstantiable (test.test_os.TestDirEntry) ... ok
test_unpickable (test.test_os.TestDirEntry) ... ok
test_blocking (test.test_os.TestInvalidFD) ... ok
test_closerange (test.test_os.TestInvalidFD) ... ok
test_dup (test.test_os.TestInvalidFD) ... ok
test_dup2 (test.test_os.TestInvalidFD) ... ok
test_fchdir (test.test_os.TestInvalidFD) ... ok
test_fchmod (test.test_os.TestInvalidFD) ... ok
test_fchown (test.test_os.TestInvalidFD) ... ok
test_fdatasync (test.test_os.TestInvalidFD) ... ok
test_fdopen (test.test_os.TestInvalidFD) ... ok
test_fpathconf (test.test_os.TestInvalidFD) ... ok
test_fstat (test.test_os.TestInvalidFD) ... ok
test_fstatvfs (test.test_os.TestInvalidFD) ... ok
test_fsync (test.test_os.TestInvalidFD) ... ok
test_ftruncate (test.test_os.TestInvalidFD) ... ok
test_inheritable (test.test_os.TestInvalidFD) ... ok
test_isatty (test.test_os.TestInvalidFD) ... ok
test_lseek (test.test_os.TestInvalidFD) ... ok
test_read (test.test_os.TestInvalidFD) ... ok
test_readv (test.test_os.TestInvalidFD) ... ok
test_tcgetpgrp (test.test_os.TestInvalidFD) ... ok
test_tcsetpgrpt (test.test_os.TestInvalidFD) ... ok
test_ttyname (test.test_os.TestInvalidFD) ... ok
test_write (test.test_os.TestInvalidFD) ... ok
test_writev (test.test_os.TestInvalidFD) ... ok
test_argument_required (test.test_os.TestPEP519) ... ok
test_bad_pathlike (test.test_os.TestPEP519) ... ok
test_fsencode_fsdecode (test.test_os.TestPEP519) ... ok
test_garbage_in_exception_out (test.test_os.TestPEP519) ... ok
test_pathlike (test.test_os.TestPEP519) ... ok
test_pathlike_class_getitem (test.test_os.TestPEP519) ... ok
test_pathlike_subclasshook (test.test_os.TestPEP519) ... ok
test_return_bytes (test.test_os.TestPEP519) ... ok
test_return_string (test.test_os.TestPEP519) ... ok
test_argument_required (test.test_os.TestPEP519PurePython) ... ok
test_bad_pathlike (test.test_os.TestPEP519PurePython) ... ok
test_fsencode_fsdecode (test.test_os.TestPEP519PurePython) ... ok
test_garbage_in_exception_out (test.test_os.TestPEP519PurePython) ... ok
test_pathlike (test.test_os.TestPEP519PurePython) ... ok
test_pathlike_class_getitem (test.test_os.TestPEP519PurePython) ... ok
test_pathlike_subclasshook (test.test_os.TestPEP519PurePython) ... ok
test_return_bytes (test.test_os.TestPEP519PurePython) ... ok
test_return_string (test.test_os.TestPEP519PurePython) ... ok
test_attributes (test.test_os.TestScandir) ... FAIL
test_bad_path_type (test.test_os.TestScandir) ... ok
test_broken_symlink (test.test_os.TestScandir) ... ok
test_bytes (test.test_os.TestScandir) ... ok
test_bytes_like (test.test_os.TestScandir) ... ok
test_close (test.test_os.TestScandir) ... ok
test_consume_iterator_twice (test.test_os.TestScandir) ... ok
test_context_manager (test.test_os.TestScandir) ... ok
test_context_manager_close (test.test_os.TestScandir) ... ok
test_context_manager_exception (test.test_os.TestScandir) ... ok
test_current_directory (test.test_os.TestScandir) ... ok
test_empty_path (test.test_os.TestScandir) ... ok
test_fd (test.test_os.TestScandir) ... ok
test_fspath_protocol (test.test_os.TestScandir) ... ok
test_fspath_protocol_bytes (test.test_os.TestScandir) ... ok
test_removed_dir (test.test_os.TestScandir) ... ok
test_removed_file (test.test_os.TestScandir) ... ok
test_repr (test.test_os.TestScandir) ... ok
test_resource_warning (test.test_os.TestScandir) ... ok
test_uninstantiable (test.test_os.TestScandir) ... ok
test_unpickable (test.test_os.TestScandir) ... ok
test_flags (test.test_os.TestSendfile) ... skipped 'requires headers and trailers support'
test_headers (test.test_os.TestSendfile) ... skipped 'requires headers and trailers support'
test_headers_overflow_32bits (test.test_os.TestSendfile) ... skipped 'requires headers and trailers support'
test_invalid_offset (test.test_os.TestSendfile) ... ok
test_keywords (test.test_os.TestSendfile) ... ok
test_offset_overflow (test.test_os.TestSendfile) ... ok
test_send_at_certain_offset (test.test_os.TestSendfile) ... ok
test_send_whole_file (test.test_os.TestSendfile) ... ok
test_trailers (test.test_os.TestSendfile) ... skipped 'requires headers and trailers support'
test_trailers_overflow_32bits (test.test_os.TestSendfile) ... skipped 'requires headers and trailers support'
test_times (test.test_os.TimesTests) ... ok
test_urandom_failure (test.test_os.URandomFDTests) ... skipped 'os.random() does not use a file descriptor'
test_urandom_fd_closed (test.test_os.URandomFDTests) ... skipped 'os.random() does not use a file descriptor'
test_urandom_fd_reopened (test.test_os.URandomFDTests) ... skipped 'os.random() does not use a file descriptor'
test_urandom_length (test.test_os.URandomTests) ... ok
test_urandom_subprocess (test.test_os.URandomTests) ... ok
test_urandom_value (test.test_os.URandomTests) ... ok
test_issue31577 (test.test_os.UtimeTests) ... ok
test_large_time (test.test_os.UtimeTests) ... skipped 'requires NTFS'
test_utime (test.test_os.UtimeTests) ... ok
test_utime_by_indexed (test.test_os.UtimeTests) ... ok
test_utime_by_times (test.test_os.UtimeTests) ... ok
test_utime_current (test.test_os.UtimeTests) ... ok
test_utime_current_old (test.test_os.UtimeTests) ... ok
test_utime_dir_fd (test.test_os.UtimeTests) ... ok
test_utime_directory (test.test_os.UtimeTests) ... ok
test_utime_fd (test.test_os.UtimeTests) ... ok
test_utime_invalid_arguments (test.test_os.UtimeTests) ... ok
test_utime_nofollow_symlinks (test.test_os.UtimeTests) ... ok
test_file_like_path (test.test_os.WalkTests) ... ok
test_walk_bad_dir (test.test_os.WalkTests) ... ok
test_walk_bottom_up (test.test_os.WalkTests) ... ok
test_walk_many_open_files (test.test_os.WalkTests) ... ok
test_walk_prune (test.test_os.WalkTests) ... ok
test_walk_symlink (test.test_os.WalkTests) ... ok
test_walk_topdown (test.test_os.WalkTests) ... ok
test_chdir (test.test_os.Win32ErrorTests) ... skipped 'Win32 specific tests'
test_chmod (test.test_os.Win32ErrorTests) ... skipped 'Win32 specific tests'
test_mkdir (test.test_os.Win32ErrorTests) ... skipped 'Win32 specific tests'
test_remove (test.test_os.Win32ErrorTests) ... skipped 'Win32 specific tests'
test_rename (test.test_os.Win32ErrorTests) ... skipped 'Win32 specific tests'
test_utime (test.test_os.Win32ErrorTests) ... skipped 'Win32 specific tests'
test_create_junction (test.test_os.Win32JunctionTests) ... skipped 'Win32 specific tests'
test_unlink_removes_junction (test.test_os.Win32JunctionTests) ... skipped 'Win32 specific tests'
test_CTRL_BREAK_EVENT (test.test_os.Win32KillTests) ... skipped 'Win32 specific tests'
test_CTRL_C_EVENT (test.test_os.Win32KillTests) ... skipped 'Win32 specific tests'
test_kill_int (test.test_os.Win32KillTests) ... skipped 'Win32 specific tests'
test_kill_sigterm (test.test_os.Win32KillTests) ... skipped 'Win32 specific tests'
test_listdir_extended_path (test.test_os.Win32ListdirTests)
Test when the path starts with '\\?\'. ... skipped 'Win32 specific tests'
test_listdir_no_extended_path (test.test_os.Win32ListdirTests)
Test when the path is not an "extended" path. ... skipped 'Win32 specific tests'
test_getfinalpathname_handles (test.test_os.Win32NtTests) ... skipped 'Win32 specific tests'
test_stat_unlink_race (test.test_os.Win32NtTests) ... skipped 'Win32 specific tests'
test_12084 (test.test_os.Win32SymlinkTests) ... skipped 'Win32 specific tests'
test_29248 (test.test_os.Win32SymlinkTests) ... skipped 'Win32 specific tests'
test_appexeclink (test.test_os.Win32SymlinkTests) ... skipped 'Win32 specific tests'
test_buffer_overflow (test.test_os.Win32SymlinkTests) ... skipped 'Win32 specific tests'
test_directory_link (test.test_os.Win32SymlinkTests) ... skipped 'Win32 specific tests'
test_file_link (test.test_os.Win32SymlinkTests) ... skipped 'Win32 specific tests'
test_isdir_on_directory_link_to_missing_target (test.test_os.Win32SymlinkTests) ... skipped 'Win32 specific tests'
test_remove_directory_link_to_missing_target (test.test_os.Win32SymlinkTests) ... skipped 'Win32 specific tests'
test_rmdir_on_directory_link_to_missing_target (test.test_os.Win32SymlinkTests) ... skipped 'Win32 specific tests'
======================================================================
FAIL: test_attributes (test.test_os.TestScandir)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/mint/Downloads/Python-3.10.5/Lib/test/test_os.py", line 4223, in test_attributes
    self.check_entry(entry, 'dir', True, False, False)
  File "/home/mint/Downloads/Python-3.10.5/Lib/test/test_os.py", line 4174, in check_entry
    self.assertEqual(entry.inode(),
AssertionError: 58992 != 10933
----------------------------------------------------------------------
Ran 316 tests in 3.339s
FAILED (failures=1, skipped=52)
test test_os failed
== Tests result: FAILURE ==
1 test failed:
    test_os
0:00:03 load avg: 0.71
0:00:03 load avg: 0.71 Re-running failed tests in verbose mode
0:00:03 load avg: 0.71 Re-running test_os in verbose mode (matching: test_attributes)
test_attributes (test.test_os.TestScandir) ... FAIL
======================================================================
FAIL: test_attributes (test.test_os.TestScandir)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/mint/Downloads/Python-3.10.5/Lib/test/test_os.py", line 4223, in test_attributes
    self.check_entry(entry, 'dir', True, False, False)
  File "/home/mint/Downloads/Python-3.10.5/Lib/test/test_os.py", line 4174, in check_entry
    self.assertEqual(entry.inode(),
AssertionError: 59211 != 11048
----------------------------------------------------------------------
Ran 1 test in 0.005s
FAILED (failures=1)
test test_os failed
1 test failed again:
    test_os
== Tests result: FAILURE then FAILURE ==
1 test failed:
    test_os
1 re-run test:
    test_os
Total duration: 4.0 sec
Tests result: FAILURE then FAILURE
make: *** [Makefile:1224: test] Error 2

В RADME сказано, что если такое происходит то скорее всего проблема в самом Python! Сам интерпретатор при этом работает, т.е я могу запустить его набрав python3.10

Вопрос: это действительно какой-то странный баг самого Python, или всё же проблема в моём окружении?
ПС: Если это баг, тогда просьба к местным сторожилам, - зарепортите его! а то мой английский оставляет желать лучшего

GUI » Изменение ячеек QTextTable » Июль 23, 2022 20:45:39

Читал доку по Qt 5 и 6, не нашел методов, которые бы позволяли менять размер ячеек QTextTable. Что нужно:

1) Возможность указать ширину каждого столбца
2) Возможность указать максимальную высоту строки
3) Если текст в ячейке не влезает полностью в ячейку, то как-то это нужно понять

Это вообще возможно? Я могу сделать такое в QTableWidget, однако, оно не поддерживает разный шрифт для одной и той же ячейки.

Python для новичков » Как установить cli app, чтобы оно запускалось глобально, не из venv » Июль 22, 2022 14:31:07

Привет, имеется простое мини-приложение со своим venv, когда я его устанавливаю внутри вирт. окружения, “pip install .” то все ок, запускается просто вызовом pkg в консоли. Как сделать, чтобы его можно было вызывать не из venv а из глобального окружения?

from setuptools import setup, find_packages

with open('requirements.txt') as rq:
required = rq.read().splitlines()

setup(
name='pkg-app',
version='0.1',
author='k',
packages=find_packages(),
include_package_data=True,
install_requires=required,
entry_points={
'console_scripts': [
'pkg = pkg:app'
]
}
)

Установка без глобального окружения тоже проходит успешно, но при запуске выдает вот такое:
PS C:\Users\pp_user\SVN\trunk\snowflake\python\scripts\dl\pkg> pkg
Traceback (most recent call last):
File “C:\Users\pp_user\AppData\Local\Programs\Python\Python39\Scripts\pkg-script.py”, line 33, in <module>
sys.exit(load_entry_point('pkg-app==0.1', ‘console_scripts’, ‘pkg’)())
File “C:\Users\pp_user\AppData\Local\Programs\Python\Python39\Scripts\pkg-script.py”, line 25, in importlib_load_entry_point
return next(matches).load()
File “C:\Users\pp_user\AppData\Local\Programs\Python\Python39\lib\importlib\metadata.py”, line 77, in load
File “C:\Users\pp_user\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py”, line 127, in import_module
return _bootstrap._gcd_import(name, package, level)
File “<frozen importlib._bootstrap>”, line 1030, in _gcd_import
File “<frozen importlib._bootstrap>”, line 1007, in _find_and_load
File “<frozen importlib._bootstrap>”, line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named ‘pkg’

Python для новичков » Seleniumwire и selenium  » Июль 13, 2022 13:33:57



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

Прокси теперь работает, но скрипт везде крашится


Оригинальный скрипт:

 try:
    from selenium import webdriver
    import time, os, ctypes, requests
    from colorama import Fore, init
    import warnings, selenium, platform
except ImportError:
    input("Error while importing modules. Please install the modules in requirements.txt")
init(convert = True, autoreset = True)
warnings.filterwarnings("ignore", category=DeprecationWarning)
clear = "clear"
if platform.system() == "Windows":
    clear = "cls"
os.system(clear)
ascii_text = f"""{Fore.RED}
                ████████▀▀▀████
                ████████────▀██
                ████████──█▄──█
                ███▀▀▀██──█████
                █▀──▄▄██──█████
                █──█████──█████
                █▄──▀▀▀──▄█████
                ███▄▄▄▄▄███████ github.com/useragents
"""
class automator:
    
    def __init__(self):
                                            
                  
                    
            
                                                                    
                                                                      
                                            
            
        
        options = webdriver.ChromeOptions()
        options.add_argument('--ignore-certificate-errors')
        options.add_experimental_option("excludeSwitches", ["enable-logging"])
        self.xpaths = {
            "followers": "/html/body/div[4]/div[1]/div[3]/div/div[1]/div/button",
            "likes": "/html/body/div[4]/div[1]/div[3]/div/div[2]/div/button",
            "views": "/html/body/div[4]/div[1]/div[3]/div/div[4]/div/button",
            "shares": "/html/body/div[4]/div[1]/div[3]/div/div[5]/div/button"
        }
        try:
            self.driver = webdriver.Chrome(options = options)
        except Exception as e:
            self.error(f"Error trying to load web driver: {e}")
        self.status = {}
        self.sent = 0
        self.cooldowns = 0
        self.ratelimits = 0
    def check_status(self):
        for xpath in self.xpaths:
            value = self.xpaths[xpath]
            element = self.driver.find_element_by_xpath(value)
            if not element.is_enabled():
                self.status.update({xpath: "[OFFLINE]"})
            else:
                self.status.update({xpath: ""})
    
    def check_for_captcha(self):
        while True:
            try:
                if "Enter the word" not in self.driver.page_source:
                    return
            except:
                return
            os.system(clear)
            print(ascii_text)
            print(f"{self.console_msg('Error')} Complete the CAPTCHA in the driver.")
            time.sleep(1)
    def console_msg(self, status):
        colour = Fore.RED
        if status == "Success":
            colour = Fore.GREEN
        return f"                {Fore.WHITE}[{colour}{status}{Fore.WHITE}]"
    
    def update_ascii(self):
        options = f"""
{self.console_msg("1")} Follower Bot {Fore.RED}{self.status["followers"]}
{self.console_msg("2")} Like Video Bot {Fore.RED}{self.status["likes"]}
{self.console_msg("3")} View Bot {Fore.RED}{self.status["views"]}
{self.console_msg("4")} Share Bot {Fore.RED}{self.status["shares"]}
        """
        return ascii_text + options
    
    def check_url(self, url):
        redirect = True
        if "vm.tiktok.com/" in url:
            redirect = False
        if redirect:
            if "/video/" not in url:
                return False
        session = requests.Session()
        r = session.get(url, allow_redirects=redirect)
        if redirect:
            if r.status_code == 200:
                return True
            return False
        location = r.headers["Location"]
        if "/video" in location:
            return True
        return False
    def convert(self, min, sec):
        seconds = 0
        if min != 0:
            answer = int(min) * 60
            seconds += answer
        seconds += int(sec) + 15
        return seconds
    def check_submit(self, div):
        remaining = f"/html/body/div[4]/div[{div}]/div/div/h4"
        try:
            element = self.driver.find_element_by_xpath(remaining)
        except:
            return None, None
        if "READY" in element.text:
            return True, True
        if "seconds for your next submit" in element.text:
            output = element.text.split("Please wait ")[1].split(" for")[0]
            minutes = element.text.split("Please wait ")[1].split(" ")[0]
            seconds = element.text.split("(s) ")[1].split(" ")[0]
            sleep_duration = self.convert(minutes, seconds)
            return sleep_duration, output
        return element.text, None
    
    def update_cooldown(self, sleep_time, bot, rl = False):
        cooldown = sleep_time
        while True:
            time.sleep(1)
            try:
                cooldown -= 1
            except TypeError:
                break
            self.update_title(bot, cooldown, rl)
            if cooldown == 0:
                break
    
    def wait_for_ratelimit(self, arg, div):
        time.sleep(1)
        duration, output = self.check_submit(div)
        if duration == True:
            return
        if output == None:
            time.sleep(0.7)
            self.wait_for_ratelimit(arg, div)
        self.cooldowns += 1
        self.update_cooldown(duration, arg)
    def send_bot(self, video_url, bot, div):
        try:
            self.driver.find_element_by_xpath(self.xpaths[bot]).click()
            time.sleep(0.5)
        except:
            pass
        enter_link_xpath = f"/html/body/div[4]/div[{div}]/div/form/div/input"
        link = self.driver.find_element_by_xpath(enter_link_xpath)
        link.clear()
        link.send_keys(video_url)
        self.driver.find_element_by_xpath(f"/html/body/div[4]/div[{div}]/div/form/div/div/button").click() #Search button
        time.sleep(0.8)
        send_button_xpath = f"/html/body/div[4]/div[{div}]/div/div/div[1]/div/form/button"
        try:
            self.driver.find_element_by_xpath(send_button_xpath).click()
        except selenium.common.exceptions.NoSuchElementException:
            self.wait_for_ratelimit(bot, div)
            self.driver.find_element_by_xpath(f"/html/body/div[4]/div[{div}]/div/form/div/div/button").click() #Search button
            time.sleep(0.8)
            self.driver.find_element_by_xpath(send_button_xpath).click()
        time.sleep(3)
        try:
            s = self.driver.find_element_by_xpath(f"/html/body/div[4]/div[{div}]/div/div/span")
            if "Too many requests" in s.text:
                self.ratelimits += 1
                self.update_cooldown(50, bot, True)
                self.send_bot(video_url, bot, div)
            elif "sent" in s.text:
                sent = 100
                if bot == "likes":
                    try:
                        sent = int(s.text.split(" Hearts")[0])
                    except IndexError:
                        sent = 30
                if bot == "views":
                    sent = 2500
                if bot == "shares":
                    sent = 500
                self.sent += sent
            else:
                print(s.text)
        except:
            self.sent += sent
        self.update_title(bot, "0")
        self.wait_for_ratelimit(bot, div)
        self.send_bot(video_url, bot, div)
    def update_title(self, bot, remaining, rl = False):
        if clear == "cls":
            os.system(clear)
            ctypes.windll.kernel32.SetConsoleTitleW(f"TikTok AIO | Sent: {self.sent} | Cooldown: {remaining}s | Developed by @useragents on Github")
            print(ascii_text)
            print(self.console_msg(self.sent) + f" Sent {bot}")
            rl_cooldown = "0"
            cooldown = "0"
            if rl:
                rl_cooldown = remaining
            else:
                cooldown = remaining
            print(self.console_msg(self.cooldowns) + f" Cooldowns {Fore.WHITE}[{Fore.RED}{cooldown}s{Fore.WHITE}]")
            print(self.console_msg(self.ratelimits) + f" Ratelimits {Fore.WHITE}[{Fore.RED}{rl_cooldown}s{Fore.WHITE}]")
    def main(self):
        if clear == "cls":
            ctypes.windll.kernel32.SetConsoleTitleW("TikTok AIO | Developed by @useragents on Github")
        self.driver.get("https://zefoy.com/")
        time.sleep(2)
        if "502 Bad Gateway" in self.driver.page_source:
            os.system(clear)
            print(ascii_text)
            input(f"{self.console_msg('Error')} This website does not allow VPN or proxy services.")
            os._exit(0)
        self.check_for_captcha()
        self.check_status()
        self.start()
    
    def error(self, error):
        print(ascii_text)
        print(f"{self.console_msg('Error')} {error}")
        time.sleep(5)
        os._exit(0)
    
    def start(self):
        os.system(clear)
        print(self.update_ascii())
        try:
            option = int(input(f"                {Fore.RED}> {Fore.WHITE}"))
        except ValueError:
            self.start()
        if option == 1:
            if self.status["followers"] != "":
                return self.start()
            div = 2
            ver = "followers"
            username = str(input(f"\n{self.console_msg('Console')} TikTok Username: @"))
            print()
            self.send_bot(username, ver, div)
            return
        elif option == 2:
            if self.status["likes"] != "":
                return self.start()
            div = 3
            ver = "likes"
        elif option == 3:
            if self.status["views"] != "":
                return self.start()
            div = 5
            ver = "views"
        elif option == 4:
            if self.status["shares"] != "":
                return self.start()
            div = 6
            ver = "shares"
        else:
            return self.start()
        video_url = str(input(f"\n{self.console_msg('Console')} Video URL: "))
        print()
        check = self.check_url(video_url)
        if not check:
            return self.error("This URL does not exist.")
        self.send_bot(video_url, ver, div)
obj = automator()
obj.main()




Вот как код выглядит после добавления прокси


 try:
    from seleniumwire import webdriver
    import time, os, ctypes, requests
    from colorama import Fore, init
    import warnings, seleniumwire, selenium, platform
except ImportError:
    input("Error while importing modules. Please install the modules in requirements.txt")
init(convert = True, autoreset = True)
warnings.filterwarnings("ignore", category=DeprecationWarning)
clear = "clear"
if platform.system() == "Windows":
    clear = "cls"
os.system(clear)
ascii_text = f"""{Fore.RED}
                ████████▀▀▀████
                ████████────▀██
                ████████──█▄──█
                ███▀▀▀██──█████
                █▀──▄▄██──█████
                █──█████──█████
                █▄──▀▀▀──▄█████
                ███▄▄▄▄▄███████ github.com/useragents
"""
class automator:
    
    def __init__(self):
        #options = webdriver.ChromeOptions()
        options = {
            'proxy':
            {
            'http': 'http://user:cmIASOd19sAZ@32.152.21.129:3128',
            'https': 'https://user:cmIASOd19sAZ@32.152.21.129:3128',
            'no_proxy': 'localhost,127.0.0.1'
            }
        }
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--ignore-certificate-errors')
        chrome_options.add_experimental_option("excludeSwitches", ["enable-logging"])
        self.xpaths = {
            "followers": "/html/body/div[4]/div[1]/div[3]/div/div[1]/div/button",
            "likes": "/html/body/div[4]/div[1]/div[3]/div/div[2]/div/button",
            "views": "/html/body/div[4]/div[1]/div[3]/div/div[4]/div/button",
            "shares": "/html/body/div[4]/div[1]/div[3]/div/div[5]/div/button"
        }
        try:
            self.driver = webdriver.Chrome('chromedriver', options=chrome_options,seleniumwire_options=options)
        except Exception as e:
            self.error(f"Error trying to load web driver: {e}")
        self.status = {}
        self.sent = 0
        self.cooldowns = 0
        self.ratelimits = 0
    def check_status(self):
        for xpath in self.xpaths:
            value = self.xpaths[xpath]
            element = self.driver.find_element_by_xpath(value)
            if not element.is_enabled():
                self.status.update({xpath: "[OFFLINE]"})
            else:
                self.status.update({xpath: ""})
    
    def check_for_captcha(self):
        while True:
            try:
                if "Enter the word" not in self.driver.page_source:
                    return
            except:
                return
            os.system(clear)
            print(ascii_text)
            print(f"{self.console_msg('Error')} Complete the CAPTCHA in the driver.")
            time.sleep(1)
    def console_msg(self, status):
        colour = Fore.RED
        if status == "Success":
            colour = Fore.GREEN
        return f"                {Fore.WHITE}[{colour}{status}{Fore.WHITE}]"
    
    def update_ascii(self):
        options = f"""
{self.console_msg("1")} Follower Bot {Fore.RED}{self.status["followers"]}
{self.console_msg("2")} Like Video Bot {Fore.RED}{self.status["likes"]}
{self.console_msg("3")} View Bot {Fore.RED}{self.status["views"]}
{self.console_msg("4")} Share Bot {Fore.RED}{self.status["shares"]}
        """
        return ascii_text + options
    
    def check_url(self, url):
        redirect = True
        if "vm.tiktok.com/" in url:
            redirect = False
        if redirect:
            if "/video/" not in url:
                return False
        session = requests.Session()
        r = session.get(url, allow_redirects=redirect)
        if redirect:
            if r.status_code == 200:
                return True
            return False
        location = r.headers["Location"]
        if "/video" in location:
            return True
        return False
    def convert(self, min, sec):
        seconds = 0
        if min != 0:
            answer = int(min) * 60
            seconds += answer
        seconds += int(sec) + 15
        return seconds
    def check_submit(self, div):
        remaining = f"/html/body/div[4]/div[{div}]/div/div/h4"
        try:
            element = self.driver.find_element_by_xpath(remaining)
        except:
            return None, None
        if "READY" in element.text:
            return True, True
        if "seconds for your next submit" in element.text:
            output = element.text.split("Please wait ")[1].split(" for")[0]
            minutes = element.text.split("Please wait ")[1].split(" ")[0]
            seconds = element.text.split("(s) ")[1].split(" ")[0]
            sleep_duration = self.convert(minutes, seconds)
            return sleep_duration, output
        return element.text, None
    
    def update_cooldown(self, sleep_time, bot, rl = False):
        cooldown = sleep_time
        while True:
            time.sleep(1)
            try:
                cooldown -= 1
            except TypeError:
                break
            self.update_title(bot, cooldown, rl)
            if cooldown == 0:
                break
    
    def wait_for_ratelimit(self, arg, div):
        time.sleep(1)
        duration, output = self.check_submit(div)
        if duration == True:
            return
        if output == None:
            time.sleep(0.7)
            self.wait_for_ratelimit(arg, div)
        self.cooldowns += 1
        self.update_cooldown(duration, arg)
    def send_bot(self, video_url, bot, div):
        try:
            self.driver.find_element_by_xpath(self.xpaths[bot]).click()
            time.sleep(0.5)
        except:
            pass
        enter_link_xpath = f"/html/body/div[4]/div[{div}]/div/form/div/input"
        link = self.driver.find_element_by_xpath(enter_link_xpath)
        link.clear()
        link.send_keys(video_url)
        self.driver.find_element_by_xpath(f"/html/body/div[4]/div[{div}]/div/form/div/div/button").click() #Search button
        time.sleep(0.8)
        send_button_xpath = f"/html/body/div[4]/div[{div}]/div/div/div[1]/div/form/button"
        try:
            self.driver.find_element_by_xpath(send_button_xpath).click()
        except selenium.common.exceptions.NoSuchElementException:
            self.wait_for_ratelimit(bot, div)
            self.driver.find_element_by_xpath(f"/html/body/div[4]/div[{div}]/div/form/div/div/button").click() #Search button
            time.sleep(0.8)
            self.driver.find_element_by_xpath(send_button_xpath).click()
        time.sleep(3)
        try:
            s = self.driver.find_element_by_xpath(f"/html/body/div[4]/div[{div}]/div/div/span")
            if "Too many requests" in s.text:
                self.ratelimits += 1
                self.update_cooldown(50, bot, True)
                self.send_bot(video_url, bot, div)
            elif "sent" in s.text:
                sent = 100
                if bot == "likes":
                    try:
                        sent = int(s.text.split(" Hearts")[0])
                    except IndexError:
                        sent = 30
                if bot == "views":
                    sent = 2500
                if bot == "shares":
                    sent = 500
                self.sent += sent
            else:
                print(s.text)
        except:
            self.sent += sent
        self.update_title(bot, "0")
        self.wait_for_ratelimit(bot, div)
        self.send_bot(video_url, bot, div)
    def update_title(self, bot, remaining, rl = False):
        if clear == "cls":
            os.system(clear)
            ctypes.windll.kernel32.SetConsoleTitleW(f"TikTok AIO | Sent: {self.sent} | Cooldown: {remaining}s | Developed by @useragents on Github")
            print(ascii_text)
            print(self.console_msg(self.sent) + f" Sent {bot}")
            rl_cooldown = "0"
            cooldown = "0"
            if rl:
                rl_cooldown = remaining
            else:
                cooldown = remaining
            print(self.console_msg(self.cooldowns) + f" Cooldowns {Fore.WHITE}[{Fore.RED}{cooldown}s{Fore.WHITE}]")
            print(self.console_msg(self.ratelimits) + f" Ratelimits {Fore.WHITE}[{Fore.RED}{rl_cooldown}s{Fore.WHITE}]")
    def main(self):
        if clear == "cls":
            ctypes.windll.kernel32.SetConsoleTitleW("TikTok AIO | Developed by @useragents on Github")
        self.driver.get("https://zefoy.com/")
        time.sleep(2)
        if "502 Bad Gateway" in self.driver.page_source:
            os.system(clear)
            print(ascii_text)
            input(f"{self.console_msg('Error')} This website does not allow VPN or proxy services.")
            os._exit(0)
        self.check_for_captcha()
        self.check_status()
        self.start()
    
    def error(self, error):
        print(ascii_text)
        print(f"{self.console_msg('Error')} {error}")
        time.sleep(5)
        os._exit(0)
    
    def start(self):
        os.system(clear)
        print(self.update_ascii())
        try:
            option = int(input(f"                {Fore.RED}> {Fore.WHITE}"))
        except ValueError:
            self.start()
        if option == 1:
            if self.status["followers"] != "":
                return self.start()
            div = 2
            ver = "followers"
            username = str(input(f"\n{self.console_msg('Console')} TikTok Username: @"))
            print()
            self.send_bot(username, ver, div)
            return
        elif option == 2:
            if self.status["likes"] != "":
                return self.start()
            div = 3
            ver = "likes"
        elif option == 3:
            if self.status["views"] != "":
                return self.start()
            div = 5
            ver = "views"
        elif option == 4:
            if self.status["shares"] != "":
                return self.start()
            div = 6
            ver = "shares"
        else:
            return self.start()
        video_url = str(input(f"\n{self.console_msg('Console')} Video URL: "))
        print()
        check = self.check_url(video_url)
        if not check:
            return self.error("This URL does not exist.")
        self.send_bot(video_url, ver, div)
obj = automator()
obj.main()




Я поменял только

 from selenium import webdriver 

в

 from seleniumwire import webdriver 


добавил прокси и


 self.driver = webdriver.Chrome(options = options) 

в


 self.driver = webdriver.Chrome('chromedriver', options=chrome_options,seleniumwire_options=options)


Может другие незначительные детали


Прокси работают, но теперь я всегда получают ошибки


 During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\user\Downloads\Zefoy-TikTok-Automator-main\Zefoy-TikTok-Automator-main\tiktok1.py", line 285, in <module>
    obj.main()
  File "C:\Users\user\Downloads\Zefoy-TikTok-Automator-main\Zefoy-TikTok-Automator-main\tiktok1.py", line 236, in main
    self.start()
  File "C:\Users\user\Downloads\Zefoy-TikTok-Automator-main\Zefoy-TikTok-Automator-main\tiktok1.py", line 282, in start
    self.send_bot(video_url, ver, div)
  File "C:\Users\user\Downloads\Zefoy-TikTok-Automator-main\Zefoy-TikTok-Automator-main\tiktok1.py", line 177, in send_bot
    except seleniumwire.webdriver.common.exceptions.NoSuchElementException:
AttributeError: module 'seleniumwire.webdriver' has no attribute 'common'
C:\Users\user\Downloads\Zefoy-TikTok-Automator-main\Zefoy-TikTok-Automator-main>

Центр помощи » Помогите срочно ребята прошу завтра сдача » Июнь 22, 2022 03:29:04

1. Дана последовательность действительных чисел a1, a2, …, аn. Указать те ее элементы, которые принадлежат отрезку .
2.Даны целые числа a1, a2, …, аn. Наименьший член этой последовательности заменить целой частью среднего арифметического всех членов, остальные члены оставить без изменения. Если в последовательности несколько наименьших членов, то заменить последний по порядку.
молю!
на питоне

Python для новичков » OpenCV » Июнь 19, 2022 00:11:25

Всем привет.

Хочу распознавать и отслеживать на видео с вебки мячик для тенниса, задаю значения HSV, вроде все хорошо, но переходя в другую комнату освещение меняется и мячик уже не так хорошо распознается.

Можно ли как-то сделать универсально ?
На уме только задать два диапазона, для тусклого и яркого освещения, и в зависимости находится ли там круг переключаться между ними, но как это реализовать не знаю ((
Подскажите пожалуйста, как это можно сделать

Если есть какая-нибудь литература на эту тему, скиньте название, буду очень благодарен

Python для новичков » Нужно решение с группами в ListWidget » Июнь 12, 2022 09:20:36

Привет!
Планирую открывать несколько папок и помещать файлы в QListWidget (поминаю, возможно QTreeView тут предпочтительнее)
В общем, на скорую руку накидал пример
 #-------------------------------------------------------------------------------
# Name:        test label in list
#
# Created:     11.06.2022
# Copyright:   (c) Novator 2022
#-------------------------------------------------------------------------------
import sys
from PyQt5 import QtWidgets, QtCore
class Test(QtWidgets.QWidget):
	def __init__(self, parent=None):
		super().__init__(parent)
		self.lst()
		self.lst.itemClicked.connect(self.check_item_in_books_list)
	def lst(self):
		self.setWindowTitle('Test')
		self.btn_base_1 = QtWidgets.QPushButton("Btn_1")
		self.lst = QtWidgets.QListWidget()
		tops = QtWidgets.QHBoxLayout()
		tops.addWidget(self.btn_base_1)
		main_layout = QtWidgets.QVBoxLayout()
		main_layout.addWidget(self.lst)
		main_layout.addLayout(tops)
		self.setLayout(main_layout)
	@staticmethod
	def check_item_in_books_list(item):
		if item.checkState() == QtCore.Qt.Checked:
			item.setCheckState(QtCore.Qt.Unchecked)
		else:
			item.setCheckState(QtCore.Qt.Checked)
	def fill_lst(self):
		label = QtWidgets.QLabel('TEST LABEL')
		grp = QtWidgets.QListWidgetItem()
		label.setAlignment(QtCore.Qt.AlignCenter)
		label.setEnabled(False)
		self.lst.addItem(grp)
		self.lst.setItemWidget(grp, label)
		for i in range(10):
			item = QtWidgets.QListWidgetItem()
			item.setText(str(i))
			item.setCheckState(QtCore.Qt.Unchecked)
			self.lst.addItem(item)
if __name__ == '__main__':
	app = QtWidgets.QApplication(sys.argv)
	window = Test()
	window.show()
	window.fill_lst()
	sys.exit(app.exec_())
В принципе, так бы устроило, но…
- как запретить чекбокс для надписи?
- при клике на надпись чтобы выделялись все элементы под ней (так сказать, вся группа)
- ну и если в группе нет элементов, чтобы удалилась со списка и сама группа

Центр помощи » Простое число » Июнь 3, 2022 15:47:10

Если задано целое число, создайте функцию, которая возвращает следующее простое число. Если число простое, верните само число.
Пример:
nextPrime(12) ➞ 13

nextPrime(24) ➞ 29

nextPrime(11) ➞ 11
// 11 is a prime, so we return the number itself.

Центр помощи » Функция, которая преобразует строку в звездную стенографию. » Июнь 3, 2022 13:29:08

Напишите функцию, которая преобразует строку в звездную стенографию. Если символ повторяется n раз, преобразуйте его в символ*n.
Пример:
toStarShorthand(“abbccc”) ➞ “ab*2c*3”

toStarShorthand(“77777geff”) ➞ “7*5gef*2”

toStarShorthand(“abc”) ➞ “abc”

toStarShorthand(“”) ➞ “”

Python для новичков » Шахматный ход » Июнь 3, 2022 08:35:19

Создайте функцию, которая принимает имя шахматной фигуры, ее положение и целевую позицию. Функция должна возвращать True, если фигура может двигаться к цели, и False, если она не может этого сделать.
Возможные входные данные - “пешка”, “конь”, “слон”, “Ладья”, “Ферзь” и “ король”.

Пример:
canMove(“Rook”, “A8”, “H8”) ➞ True

canMove(“Bishop”, “A7”, “G1”) ➞ True

canMove(“Queen”, “C4”, “D6”) ➞ False

Python для новичков » Звездная стенография » Июнь 3, 2022 08:33:06

Напишите функцию, которая преобразует строку в звездную стенографию. Если символ повторяется n раз, преобразуйте его в символ*n.
Пример:
toStarShorthand(“abbccc”) ➞ “ab*2c*3”

toStarShorthand(“77777geff”) ➞ “7*5gef*2”

toStarShorthand(“abc”) ➞ “abc”

toStarShorthand(“”) ➞ “”

Python для новичков » сумма чисел главной диагонали матрицы » Июнь 1, 2022 10:33:44

Привет, помогите решить задачу.
Нужно найти сумму чисел главной диагонали матрицы, код я написал, в Pycharm все работает как положено, все считает, но при попытке сдать задачу (онлайн курс, там автоматическая система проверки), выдает ошибку в этой строке
 matrix[i][j] = int(input()).split()
ошибка такого вида ValueError: invalid literal for int() with base 10: ‘1 2 3’
не пойму как исправить, я понимаю что тип входных данных не соответствует, уже все перепробовал никак не могу разобраться.
вот код:
 # задаем размерность, пустой список и счетчик для матрицы
rows = int(input())
matrix = []
count = 0
# создаем вложенный список для будущей матрицы заполненный нулями
for _ in range(rows):
    matrix.append([0] * rows)
# заполняем матрицу произвольными значениями и сразу вычисляем сумму чисел главной диагонали
for i in range(rows):
    for j in range(rows):
        matrix[i][j] = int(input())
        if (i == j):                       # это индексы элементов, а не значения
            count += matrix[i][j]   # а здесь уже значения соответствующие этим индексам
# выводим матрицу на экран
for r in range(rows):
    for c in range(rows):
        print(str(matrix[r][c]).rjust(3), end=' ')
    print()
# принтуем сумму чисел главной диагонали
print(count)

Центр помощи » Срочно нужна помощь, добрые люди. В универе задали задачи, которые никак не могу решить, время куда-то улетает. » Май 31, 2022 17:22:47

1) Задана квадратная матрица. Переставить строку с максимальным элементом на главной диагонали со строкой с заданным номером m.
2) Составить программу, которая заполняет квадратную матрицу порядка п натуральными числами 1, 2, 3, …, n2, записывая их в нее «по спирали».
3) Составить программу для нахождения чисел из интервала , имеющих наибольшее количество делителей.
4) Четыре точки заданы своими координатами X(x1, x2), Y(y1, y2), Z(z1, z2), P(p1, p2). Выяснить, какие из них находятся на максимальном расстоянии друг от друга и вывести на экран значение этого расстояния. Вычисление расстояния между двумя точками оформить в виде процедуры.

Буду очень благодарен, как обычно, застрял на половине

Центр помощи » помогите пожалуйста с транслитерацией и заменой букв в том же самом файле » Май 31, 2022 15:14:24

Доброго дня!
заранее спасибо за помощь
дело такое, делаю генератор паролей(я новичок, так что за код не агритесь пжлст)
нашел транслитерацию и переделал под себя, но не могу сделать так, что бы файл считывался и перезаписывался уже с переведёнными буквами

вот часть кода

def transliteration(text):
cyrillic = ‘абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ’
latin = ‘a|b|v|g|d|e|e|zh|z|i|i|k|l|m|n|o|p|r|s|t|u|f|kh|tc|ch|sh|shch||y||e|iu|ia|A|B|V|G|D|E|E|Zh|Z|I|I|K|L|M|N|O|P|R|S|T|U|F|Kh|Tc|Ch|Sh|Shch||Y||E|Iu|Ia’.split('|')
return text.translate({ord(k):v for k,v in zip(cyrillic,latin)})

if __name__ == “__main__”:
s = input() #тут как раз таки вместо ввода мне нужно сделать считывание и перезапись текста, но сколько я не бился так и не смог понять(
print(transliteration(s))

весь код не стал кидать так как там много всего, не буду запутывать еще больше

Центр помощи » Нужна помощь с задачкой,от которой зависит судьба моего обучения( » Май 31, 2022 13:57:10

Знающие люди,помогите,пожалуйста
Сам не справляюсь
Могу и денежку небольшую заплатить,если нужно будет

Нужно написать модуль,который создает декораторы для методов класса.
Класс text - Строка связанного текста со знаками препинания
Методы:
1.Исправление текста так,чтобы предложения начинались с заглавной буквы
2. Удаление символов,которые не являются допустимыми в тексте.
Декораторы:
1.Перевод всех бук в заглавные
2 Разбиение текста на список предложений