I want a python script to login into Facebook account by cookie
- User
I want a python script to login into Facebook account by cookie
- Assistant
Sure, I can help guide you through writing a Python script to log into a Facebook account using cookies. Using cookies for web automation often involves leveraging libraries like
SeleniumorRequestsin combination with a tool likeBrowserCookie3to extract cookies. Below, I’ll provide an example usingSelenium.Disclaimer:
- Automating interactions with Facebook might violate Facebook's Terms of Service.
- Be cautious when running scripts that automate login processes as it exposes sensitive information.
- The following example is for educational purposes only.
Here's a Python script using Selenium to log into Facebook using cookies:
- Install Required Libraries:
Make sure you have
seleniumandbrowser-cookie3installed. You can install these using pip:
bashpip install selenium browser-cookie3- Script to Automate Login with Cookies:
pythonfrom selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager import browser_cookie3 # Initialize the Chrome browser service = Service(ChromeDriverManager().install()) options = webdriver.ChromeOptions() # You can add options here to customize the browser experience browser = webdriver.Chrome(service=service, options=options) browser.get('https://www.facebook.com') # Extract cookies for Facebook from your browser fb_cookies = browser_cookie3.chrome(domain_name='.facebook.com') # Add extracted cookies to the browser for cookie in fb_cookies: cookie_dict = { 'name': cookie.name, 'value': cookie.value, 'domain': cookie.domain, 'path': cookie.path, 'expiry': cookie.expires, 'httpOnly': cookie.has_nonstandard_attr('HttpOnly') } if cookie.secure: cookie_dict['secure'] = True print(f"Adding cookie: {cookie_dict}") browser.add_cookie(cookie_dict) # Refresh the page to log in using added cookies browser.refresh() # Optionally, add some logic to verify login succeeded try: browser.find_element(By.XPATH, '//div[text()="Home"]') # Replace with an element that confirms login print("Login successful!") except: print("Login failed.") # Remember to close the browser # browser.quit()