用Selenium Python和Firefox重新打開相同的瀏覽器視窗

2024-10-03 13:19:42 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,我正在尝试制作一个自动程序来发送Whatsapp消息。 我目前正在使用python、Firefox和selenium来实现这一目标。 问题是每次我调用driver.get(url)时,它都会打开一个新的firefox浏览器实例,空白的,没有上次运行的记忆。它让我每次运行它都会扫描条形码。在

from selenium import webdriver
from selenium.webdriver.firefox.webdriver import FirefoxProfile

cp_profile = webdriver.FirefoxProfile("/Users/Hodai/AppData/Roaming/Mozilla/Firefox/Profiles/v27qat5d.whatsapp_profile")
driver = webdriver.Firefox(executable_path="/Users/Hodai/Desktop/geckodriver",firefox_profile=cp_profile)
driver.get('http://web.whatsapp.com')

#Scan the code before proceeding further
input('Enter anything after scanning QR code')

我试过使用个人资料,但似乎没有影响。在

^{pr2}$

Tags: fromimportgetdriverseleniumcodefirefoxprofile
3条回答

最后我用了chromedriver实现了我的目标。 我试过泡菜饼干,但有点棘手,因为它只记得同一个域名的饼干。 所以我使用了chrome的用户数据。 现在它就像一个符咒。谢谢大家。在

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("user-data-dir=C:/Users/Designer1/AppData/Local/Google/Chrome/User Data/Profile 1")
driver = webdriver.Chrome(chrome_options=options,executable_path="C:\webdrivers\chromedriver.exe")

不应该是那样的。它只在用新变量初始化或程序再次启动时打开新窗口。这是chrome的代码。不管你调用driver.get(url)多少次,它都会在同一个浏览器窗口中打开url

from selenium import webdriver
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome(executable_path=r"C:\new\chromedriver.exe")
driver.get('https://www.olx.com.pk/lahore/apple/q-iphone-6s/?search%5Bfilter_float_price%3Afrom%5D=40000&search%5Bfilter_float_price%3Ato%5D=55000')
time.sleep(10)
driver.get('https://www.olx.com.pk/lahore/apple/q-iphone-6s/?search%5Bfilter_float_price%3Afrom%5D=40000&search%5Bfilter_float_price%3Ato%5D=55000')
time.sleep(10)
driver.get('https://www.olx.com.pk/lahore/apple/q-iphone-6s/?search%5Bfilter_float_price%3Afrom%5D=40000&search%5Bfilter_float_price%3Ato%5D=55000')
time.sleep(10)

如果问题解决了,或者你想做其他事情,请告诉我。在

我认为最简单的方法是扫描qrcode后保存cookies,并手动将它们推送到Selenium。在

# Load page to be able to set cookies
driver.get('http://web.whatsapp.com')

# Set saved cookies
cookies = {'name1': 'value1', 'name2', 'value2'}
for name in cookies:
    driver.add_cookie({
        'name': name,
        'value': cookies[name],
    })

# Load page using cookies
driver.get('http://web.whatsapp.com')

要获取cookies,可以使用控制台(F12)的“网络”选项卡,右键单击请求,Copy=>;Copy request Headers。在

相关问题 更多 >