Spaces:
Runtime error
Runtime error
import asyncio | |
from pathlib import Path | |
from playwright.async_api import async_playwright, TimeoutError as PlaywrightTimeoutError | |
async def post_to_facebook(email: str, password: str, message: str, image_path: str = None): | |
async with async_playwright() as p: | |
browser = await p.chromium.launch(headless=False) # headless=True إذا تريد بدون واجهة | |
context = await browser.new_context() | |
page = await context.new_page() | |
try: | |
print("[*] تسجيل الدخول...") | |
await page.goto("https://www.facebook.com/", timeout=30000) | |
# انتظر حقول البريد وكلمة السر قبل تعبئتها | |
await page.wait_for_selector('input[name="email"]', timeout=15000) | |
await page.fill('input[name="email"]', email) | |
await page.fill('input[name="pass"]', password) | |
await page.click('button[name="login"]') | |
# انتظر ظهور زر إنشاء منشور بعد تسجيل الدخول | |
await page.wait_for_selector('div[aria-label="إنشاء منشور"]', timeout=20000) | |
print("[*] فتح نافذة المنشور...") | |
await page.click('div[aria-label="إنشاء منشور"]') | |
await page.wait_for_selector('div[role="textbox"]', timeout=10000) | |
# استخدام focus ثم keyboard.type لكتابة الرسالة بطريقة أكثر ثباتاً | |
textbox = await page.query_selector('div[role="textbox"]') | |
await textbox.focus() | |
await page.keyboard.type(message, delay=50) # تأخير بسيط لمحاكاة الكتابة البشرية | |
# رفع صورة إذا مسارها صحيح | |
if image_path and Path(image_path).is_file(): | |
print("[*] رفع الصورة...") | |
file_input = await page.query_selector('input[type="file"]') | |
if file_input: | |
await file_input.set_input_files(image_path) | |
# انتظر قليلاً حتى تكتمل عملية الرفع | |
await page.wait_for_timeout(5000) | |
else: | |
print("[!] لم يتم العثور على عنصر رفع الملف.") | |
print("[*] النشر جارٍ...") | |
await page.click('div[aria-label="نشر"]') | |
# انتظر لتأكيد النشر أو ظهور إشعار بنجاح العملية (يمكن تحسينه لاحقاً) | |
await page.wait_for_timeout(5000) | |
print("[✓] تم النشر بنجاح.") | |
except PlaywrightTimeoutError as te: | |
print("[!] انتهت مهلة الانتظار:", te) | |
except Exception as e: | |
print("[!] حدث خطأ:", e) | |
finally: | |
await browser.close() | |
print("[*] تم إغلاق المتصفح.") | |
# مثال للاستخدام | |
if __name__ == "__main__": | |
email = "your-email@example.com" | |
password = "your-password" | |
message = "منشور جديد مع صورة!" | |
image_path = "path/to/your/image.jpg" # ضع المسار الصحيح هنا، أو None لبدون صورة | |
asyncio.run(post_to_facebook(email, password, message, image_path)) | |