使用 Selenium,可以使用浏览器 cookie 在会话之间保持登录状态

问题描述 投票:0回答:1

我想使用 Selenium 购买产品,但每次打开浏览器并注册购买时,我都需要再次登录商店网站才能完成购买。我不希望事情变成这样。我只想向机器人提供一次用户名和密码,这样每次打开浏览器时,它都会自动登录该网站。
这是我的代码的相关部分:


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import time
def admin():
        url = r"https://www.digikala.com/product/dkp-14079846/"
        # Path to your Chrome user data directory
        chrome_profile_path = r'C:\Users\mehrab\AppData\Local\Google\Chrome\User'

        # Configure Chrome options to use the specified user data directory
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument(f'--user-data-dir={chrome_profile_path}')

        # Start a new instance of Chrome with the configured options
        driver = webdriver.Chrome(options=chrome_options)
        driver.maximize_window()
        driver.get(url)

        def select_color():
            
            WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='bg-neutral-000 flex items-center justify-center cursor-pointer ml-2 px-2 lg:px-0 styles_InfoSectionVariationColor__pX_3M styles_InfoSectionVariationColor__selected__MqDpU']"))).click()
        select_color()

        # Add a wait before clicking the "add-to-cart" button
        add_to_cart_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='add-to-cart']")))
        add_to_cart_button.click()
        time.sleep(10)  # You can replace this with a more appropriate wait if needed
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.relative.inline-flex.pr-2.pl-0.lg\:p-2.bg-neutral-000.rounded.py-2"))).click()
        time.sleep(10)
        WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(text(), 'تایید و تکمیل سفارش')]"))).click()
admin()
        

事实上,我想输入一次用户名和密码,这样每次机器人运行时,我就不需要使用站点cookie登录,并且注册的产品将自动添加到我的帐户中。

python python-3.x selenium-webdriver selenium-chromedriver webdriver
1个回答
0
投票

如何使用Python + Selenium WebDriver保存和加载cookie。这将保存所有 cookie(我假设登录会话可以工作,但它可能在大多数网站上都可以工作,因此一旦登录一次,您将再次登录。

© www.soinside.com 2019 - 2024. All rights reserved.