Веб-скрепинг с помощью Python, Selenium и Tor: Мощная комбинация для парсинга.
import subprocess
import time
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.firefox.options import Options
# Define the command to start Tor. This will depend on your operating system and configuration.
command = '<<path_to_tor>>/tor.exe'
# Start the Tor process
tor_process = subprocess.Popen(command, stdout=subprocess.PIPE)
# Wait for Tor to start up
time.sleep(5)
# Sets up proxy settings for the Firefox browser driver
proxy_settings = Proxy({
'proxyType': ProxyType.MANUAL,
'socksProxy': '127.0.0.1:9050',
'socksVersion': 5
})
options = Options()
options.proxy = proxy_settings
driver = webdriver.Firefox(options=options)
driver.get('https://check.torproject.org') # Check if we are using Tor
# When you're done, don't forget to stop the Tor process
tor_process.terminate()
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Solving Captcha with Puppeteer and Python
Решение кпчи с помощью Puppeteer и Python.
@pythonl
Решение кпчи с помощью Puppeteer и Python.
import asyncio
from pyppeteer import launch
from capsolver_api import HCaptchaTask
async def main():
url = 'https://accounts.hcaptcha.com/demo'
browser = await launch(headless=False)
page = await browser.newPage()
await page.goto(url)
element = await page.querySelector('#hcaptcha-demo')
website_key = await page.evaluate('(element) => element.getAttribute("data-sitekey")', element)
capsolver = HCaptchaTask('your_capsolver_api_key')
task_id = capsolver.create_task(task_type='HCaptchaTaskProxyLess',
website_url=url,
website_key=website_key
)
captcha_key = capsolver.get_solution(task_id)
await page.waitForSelector('iframe')
await page.type('textarea[name="h-captcha-response"]', captcha_key)
await page.click('input[type="submit"]')
await page.waitFor(2000)
await page.screenshot({'path': 'solve.png'}) # screenshot of the solved captcha
asyncio.get_event_loop().run_until_complete(main())
@pythonl
This media is not supported in your browser
VIEW IN TELEGRAM
Python & command-line tool to gather text on the Web: web crawling/scraping, extraction of text, metadata, comments
Это Python бибилиотека и инструмент командной строки для парсинга и сбора текста с сайтов.
Инструмент способен к сбору основного текста, метаданных и комментариев.
▪Github
▪Tutorials
▪Python Notebook
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Тестирование FastAPI с асинхронной сессией базы данных.
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
Руководство по выполнению кода Python в HTML.
Веб-приложение, выполняющее анализ настроений в тексте, предоставленном пользователем, с помощью предварительно обученной модели машинного обучения на языке Python.
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
🎤🔤 Embrace the Power of Speech-to-Text in Python!
Представляет собой пошаговый пример кода на языке Python, использующий библиотеку SpeechRecognition для преобразования речи в текст.
@pythonl
Представляет собой пошаговый пример кода на языке Python, использующий библиотеку SpeechRecognition для преобразования речи в текст.
pip install SpeechRecognition
import speech_recognition as sr
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Say something...")
recognizer.adjust_for_ambient_noise(source) # Optional: Adjust for background noise
audio = recognizer.listen(source)
audio_file = "path/to/your/audio_file.wav" # Replace with the path to your audio file
with sr.AudioFile(audio_file) as source:
audio = recognizer.listen(source)
try:
print("Converting speech to text...")
text = recognizer.recognize_google(audio)
print("You said:", text)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand the audio.")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
@pythonl
🔢 How To Code a Simple Number Guessing Game in Python
Пишем игру для угадывания чисел на Python.
@pythonl
Пишем игру для угадывания чисел на Python.
# main.py
import random
# define range and max_attempts
lower_bound = 1
upper_bound = 1000
max_attempts = 10
# generate the secret number
secret_number = random.randint(lower_bound, upper_bound)
# Get the user's guess
def get_guess():
while True:
try:
guess = int(input(f"Guess a number between {lower_bound} and {upper_bound}: "))
if lower_bound <= guess <= upper_bound:
return guess
else:
print("Invalid input. Please enter a number within the specified range.")
except ValueError:
print("Invalid input. Please enter a valid number.")
# Validate guess
def check_guess(guess, secret_number):
if guess == secret_number:
return "Correct"
elif guess < secret_number:
return "Too low"
else:
return "Too high"
# track the number of attempts, detect if the game is over
def play_game():
attempts = 0
won = False
while attempts < max_attempts:
attempts += 1
guess = get_guess()
result = check_guess(guess, secret_number)
if result == "Correct":
print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")
won = True
break
else:
print(f"{result}. Try again!")
if not won:
print(f"Sorry, you ran out of attempts! The secret number is {secret_number}.")
if __name__ == "__main__":
print("Welcome to the Number Guessing Game!")
play_game()
@pythonl
📩 Python Email Automation: Enhancing Efficiency and Productivity with Streamlined Operations
Автоматизация отправки электронной почты на Python: Повышение эффективности и производительности за счет оптимизации операций.
@pythonl
Автоматизация отправки электронной почты на Python: Повышение эффективности и производительности за счет оптимизации операций.
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def read_excel(file_name):
data = pd.read_excel(file_name, engine='openpyxl')
return data
def send_email(receiver_address, sender_address, sender_pass, subject, body):
msg = MIMEMultipart()
msg['From'] = sender_address
msg['To'] = receiver_address
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
# Use the appropriate SMTP server
# For Gmail
server = smtplib.SMTP('smtp.gmail.com', 587)
# For Office 365
# server = smtplib.SMTP('smtp.office365.com', 587)
# For iCloud
# server = smtplib.SMTP('smtp.mail.me.com', 587)
server.starttls()
server.login(sender_address, sender_pass)
text = msg.as_string()
server.sendmail(sender_address, receiver_address, text)
server.quit()
def automate_emails(data_frame, sender_address, sender_pass, subject):
for index, row in data_frame.iterrows():
send_email(row['email'], sender_address, sender_pass, subject, f"Hello {row['name']},\n{row['message']}")
data_frame = read_excel('emailsend.xlsx')
# Replace '[email protected]' and 'your-password' with your own credentials. Pass the app password as the third parameter.
automate_emails(data_frame, '', '', '')
@pythonl
Парсер вопросов StackOverflow на Python.
from bs4 import BeautifulSoup
import requests
import json
fmt = "https://stackoverflow.com/questions/tagged/{tag}?tab={filter}&pagesize=15"
filters = [
"1. Newest",
"2. Active",
"3. Bounties",
"4. Unanswered",
"5. Frequent",
"6. Votes",
]
tag = input("enter any question tag (python, java)\n")
print("\n".join(filters))
filter = int(input("enter the filter number (1, 3, 5)\n"))
try:
filter = filters[filter].split(" ")[-1]
except:
filter = "Votes"
# generate dynamic URL with user preferences
URL = fmt.format(tag=tag, filter=filter)
print("generated URL ", URL)
content = requests.get(URL).content
soup = BeautifulSoup(content, "lxml")
# return only question tags
def is_question(tag):
try:
return tag.get("id").startswith("question-summary-")
except:
return False
questions = soup.find_all(is_question)
question_data = []
if questions:
# extract question data like votes, title, link and date
for question in questions:
question_dict = {}
question_dict["votes"] = (
question.find(class_="s-post-summary--stats-item-number").get_text().strip()
)
h3 = question.find(class_="s-post-summary--content-title")
question_dict["title"] = h3.get_text().strip()
question_dict["link"] = "https://stackoverflow.com" + h3.find("a").get("href")
question_dict["date"] = (
question.find(class_="s-user-card--time").span.get_text().strip()
)
question_data.append(question_dict)
with open(f"questions-{tag}.json", "w") as f:
json.dump(question_data, f)
print("file exported")
else:
print(URL)
print("looks like there are no questions matching your tag ", tag)
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Лучший способ получать свежие обновлении и следить за трендами в разработке.
Python: t.me/pro_python_code
C#: t.me/csharp_ci
C/C++/ t.me/cpluspluc
Машинное обучение: t.me/ai_machinelearning_big_data
Data Science: t.me/data_analysis_ml
Devops: t.me/devOPSitsec
Go: t.me/Golang_google
Базы данных: t.me/sqlhub
Rust: t.me/rust_code
Javascript: t.me/javascriptv
React: t.me/react_tg
PHP: t.me/phpshka
Android: t.me/android_its
Мобильная разработка: t.me/mobdevelop
Linux: t.me/+A8jY79rcyKJlYWY6
Big Data: t.me/bigdatai
Хакинг: t.me/linuxkalii
Java: t.me/javatg
Папка Go разработчика: t.me/addlist/MUtJEeJSxeY2YTFi
Папка Python разработчика: t.me/addlist/eEPya-HF6mkxMGIy
🇬🇧Английский: t.me/english_forprogrammers
Please open Telegram to view this post
VIEW IN TELEGRAM
Скрипт для извлечения всех сохраненных wi-fi паролей в текстовый файл.
import subprocess
import re
# Get all the Wi-Fi profiles (ssid)
out = subprocess.check_output("netsh wlan show profiles").decode()
# Filter out only profile names from the output
matches = re.findall(r"(All User Profile)(.*)", out)
# List comprehension to remove any \n \r \t and spaces
profiles = [str(match[1]).split(":")[1].strip() for match in matches]
# File object to store passwords with ssid
with open("passwords.txt", "w+") as f:
# Traversing each profile
for profile in profiles:
# try/except block to keep the script from crashing if there was an error while execution
try:
# Get password using key=clear flag
get_pass = subprocess.check_output(
f'netsh wlan show profile "{profile}" key=clear'
).decode()
# Filter out the Password line from the output
pass_by_profile = re.search(r"(Key Content)(.*)", get_pass)
# Check if the password is present or wi-fi was open
if pass_by_profile:
password = pass_by_profile.group().split(":")[1].strip()
else:
password = "THE WIFI IS OPEN"
# Write the profile name and password to the text file
f.write(f"{profile} : {password}\n")
except Exception:
continue
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Создание генератора паролей с графическим интерфейсом на Python.
import random
import string
import tkinter as tk
import pyperclip
root = tk.Tk()
root.geometry('500x500')
root.title('PASSWORD GENERATOR')
letters = string.ascii_letters
digits = string.digits
special_chars = string.punctuation
alphabet = letters + digits + special_chars
pwd_length = ''
pwd = ''
def create_pass():
global alphabet
global pwd_length
global pwd
pwd_length = int(pass_length.get())
pwd = ''
for i in range(pwd_length):
pwd += ''.join(random.choice(alphabet))
text_result.config(text=pwd)
def copy_pwd():
if pwd == '':
lbl_alert.config(text='Create a password first')
else:
pyperclip.copy(pwd)
lbl_alert.config(text='Succesfuly copied')
text_result = tk.Label(root, text='')
text_result.pack()
pass_length = tk.Entry(root)
pass_length.pack()
btn = tk.Button(root, text='Start', command=create_pass)
btn.pack()
btn_copy = tk.Button(root, text='Copy to clipboard', command=copy_pwd)
btn_copy.pack()
lbl_alert = tk.Label(root, text='')
lbl_alert.pack()
root.mainloop()
@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM