что стоит учить, чтобы стать действительно хорошим специалистом в бэкенд разработке
def has_char(string, char):
i = 0
while i < len(string):
if char == string[i].lower():
return True
if char == string[i].upper():
return True
i += 1
return False
print(has_char('Hello', 'h')) # True
print(has_char('Hello', 'H')) # True
print(has_char('Hello', 'ё')) # False, ;)
def has_char(string, char):
for i in range(len(string)):
if char == string[i]:
# if char.lower() == string[i].lower():
return True
return False
print(has_char("Привет", "п")) # True? False!
def has_char(string, char):
for _char in string:
if _char.lower() == char.lower():
return True
return False
print(has_char('Hello', 'h')) # True
print(has_char('Hello', 'H')) # True
print(has_char('Hello', 'ё')) # False, ;)
Как нажать кнопку на сайте пика через селениум?
# pahe = driver.find_element(By.CLASS_NAME, 'sc-gsnTZi fWJuXR').click()
pahe = driver.find_element(By.CSS_SELECTOR, '.sc-gsnTZi.fWJuXR').click()
И, если есть минутка - на скок понял это проверка сертификатов - как это поправить можно? (куда посмотреть)
[8468:12460:0214/095050.752:ERROR:ssl_client_socket_impl.cc(974)] handshake failed; returned -1, SSL error code 1, net_error -101
[8468:12460:0214/095050.866:ERROR:ssl_client_socket_impl.cc(974)] handshake failed; returned -1, SSL error code 1, net_error -101
$ pip install --upgrade webdriver-manager
$ pip install Pillow
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from PIL import Image
from webdriver_manager.microsoft import EdgeChromiumDriverManager
driver = webdriver.Edge(service=Service(EdgeChromiumDriverManager().install()))
driver.get("https://pillow.readthedocs.io/en/stable/installation.html")
path = "full.png"
driver.save_screenshot(path)
driver.quit()
x = 100
y = 100
w = 500
h = 300
image = Image.open(path)
cropped = image.crop((x, y, x+w, y+h))
cropped.save("crop.png")
Как передать собственный класс на метод в качестве параметра по умолчании?
Можно ли такое осуществлять? Или такое не стоит сделать даже если возможно?
class Test:
def test(self, x=None):
if x is None:
x = Test()
print(type(x))
x = Test()
x.test()
в Pyrogram документации не нашел подобного
import asyncio
from pyrogram import Client
from pyrogram.errors import PyrogramError
class ProxyManager:
def __init__(self, app, max_retries=5, retry_delay=1, proxy=None):
self.app = app
self.max_retries = max_retries
self.retry_delay = retry_delay
self.proxy = proxy
self.client = None
async def connect(self):
for attempt in range(1, self.max_retries + 1):
try:
print(f"Connection attempt #{attempt}")
self.client = Client(**self.app, proxy=self.proxy)
await self.client.start()
print("The connection was established successfully.")
except PyrogramError as e:
print(f"Connection error: {e}")
if attempt == self.max_retries:
print("The maximum number of connection attempts has been reached, stop!")
break
await asyncio.sleep(self.retry_delay)
async def disconnect(self):
if self.client:
await self.client.stop()
print("Connection is closed.")
app = {
'api_id': 'YOUR_API_ID',
'api_hash': 'YOUR_API_HASH',
'session_name': 'your_session_name'
}
proxy = {
'scheme': 'http', # or 'socks5'
'hostname': 'your.proxy.hostname',
'port': 1080,
'username': 'user',
'password': 'password'
}
# test run
async def main():
manager = ProxyManager(app, max_retries=3, retry_delay=2, proxy=proxy)
await manager.connect()
await manager.disconnect()
asyncio.run(main())
как я могу его проверить на вредоносный код, не имея навыков в програмировании на Python?
Своими глазами я вряд ли увижу, то чего стоило бы опасаться.
Есть ли какие то инструменты для выявления того, чего не должно быть в коде?
from openpyxl import load_workbook
wb = load_workbook('sheet.xlsx')
sheet = wb.active
for row in sheet.iter_rows():
for cell in row:
print(cell.row)
break
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium_stealth import stealth
proxy = '45.132.75.19:23820'
options = Options()
options.add_argument('--proxy-server=socks5://' + proxy)
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument("window-size=1920,1080")
# options.add_argument("--incognito")
options.add_argument("--disable-extensions")
options.add_argument("--disable-plugins-discovery")
options.add_argument("--start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
executable_path = './chromedriver-121.0.6167.85.exe'
service = Service(executable_path=executable_path)
driver = webdriver.Chrome(service=service, options=options)
stealth(driver,
languages=["en-US", "en"],
vendor="Google Inc.",
platform="Win64",
webgl_vendor="Intel Inc.",
renderer="Intel Iris OpenGL Engine",
fix_hairline=True,
run_on_insecure_origins=True,
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.6167.85 Safari/537.36',
)
try:
driver.get('https://allegro.pl/kategoria/laptopy-491')
time.sleep(30)
print(driver.page_source)
finally:
driver.quit()
Пытался забрать html простым реквестом, получалась не очень
попробовал через selenium - получил то же самое
import requests
import socks
import socket
socks.set_default_proxy(socks.SOCKS5, "45.56.219.55", 52759)
socket.socket = socks.socksocket
url = 'https://www.skiddle.com/festivals/dates.html'
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'}
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
print(response.text)
except requests.exceptions.HTTPError as errh:
print("Http Error:", errh)
except requests.exceptions.ConnectionError as errc:
print("Connecting Error:", errc)
except requests.exceptions.Timeout as errt:
print("Timeout Error:", errt)
except requests.exceptions.RequestException as err:
print("Other Error", err)
<!DOCTYPE html>
<!--[if lt IE 7]><html class='ie ie6 lte9 lte8 lte7 no-js'> <![endif]-->
<!--[if IE 7]><html class='ie ie7 lte9 lte8 lte7 no-js'> <![endif]-->
<!--[if IE 8]><html class='ie ie8 lte9 lte8 no-js'> <![endif]-->
<!--[if IE 9]><html class='ie ie9 lte9 no-js'> <![endif]-->
<!--[if gt IE 9]><html class='ie no-js'><![endif]-->
<!--[if !IE]><!--> <html class='no-ie no-js' lang='en'><!--<![endif]-->
<head><!-- Basic Page Needs
================================================== -->
<title>A-Z of Future Festivals</title>
<link rel="manifest" href="/manifest.json">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><!-- DNS Prefetching
================================================== -->
<link rel="preconnect" href="https://d31fr2pwly4c4s.cloudfront.net"/>
<link rel="preconnect" href="https://d1plawd8huk6hh.cloudfront.net"/>
<link rel="preconnect" href="https://www.google-analytics.com" />
<link rel="preload" href="https://d1plawd8huk6hh.cloudfront.net/css-responsive2/fonts/BuenosAires/BuenosAiresWeb1-Regular_gdi.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://d1plawd8huk6hh.cloudfront.net/css-responsive2/fonts/BuenosAires/BuenosAiresWeb1-Bold_gdi.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="dns-prefetch" href="https://d31fr2pwly4c4s.cloudfront.net"/>
<link rel="dns-prefetch" href="https://d1plawd8huk6hh.cloudfront.net"/>
<link rel="dns-prefetch" href="https://www.google-analytics.com" />
<link rel="dns-prefetch" href="//connect.facebook.net" />
<link rel="dns-prefetch" href="//www.googleadservices.com" />
<link rel="dns-prefetch" href="//www.stay22.com" />
<link rel="dns-prefetch" href="//api.stay22.com" />
<link rel="dns-prefetch" href="//skiddle.imgix.net" />
<link rel="dns-prefetch" href="//skiddleartists.imgix.net" />
<!-- CSS
================================================== -->
<meta property="fb:app_id" content="102483650494"/>
<meta http-equiv="x-dns-prefetch-control" content="on"/>
<meta name="insight-app-sec-validation" content="5574b896-289f-48c0-aebb-98730b831151">
<!-- Mobile Specific Metas
================================================== -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
...
got an unexpected keyword argument 'verify_ssl'
def f(string, index, length):
return not (length < 0 or index < 0 or index >= len(string) or length + index > len(string))
string = 'Winter is coming'
print(f(string, 4, 4))
# True
print(f(string, 4, -1))
# False
print(f(string, -1, 4))
# False
print(f(string, len(string), 4))
# False
print(f(string, len(string) - 3, 5))
# False
Что делает единичная звездочка в аргументах метода Python?
namedtuple(
typename,
field_names,
*,
rename=False,
defaults=None,
module=None,
)
Ни разу не встречал такое раньше, в документации тоже не смог откопать
Какие есть способы для решения задачи (желательно из ЯП использовать python)
Тинькофф сбрасывает любые сессии каждые 12 часов
Проблемы возникают на моменте ввода кода из смс, как его можно перенаправить серверу?
Это должно работать постоянно и не прерывно, нужен ли для этого сервер и как это сделать?
нужен ли для этого сервер