简体   繁体   English

如何在 python 中使用 selenium 访问 whatsapp web?

[英]how do I acces whatsapp web with selenium in python?

So I am using geckodriver.exe (for Firefox), and I use the following code to acces whatsapp web:所以我正在使用 geckodriver.exe(用于 Firefox),并使用以下代码访问 whatsapp web:

from selenium import webdriver
browser = None
def init():
    browser = webdriver.Firefox(executable_path=r"C:/Users/Pascal/Desktop/geckodriver.exe")
    browser.get("https://web.whatsapp.com/")
init()

But everytime I rerun the code, the QR-Code from whatsappweb has to be scanned again and I dont want that.但是每次我重新运行代码时,都必须再次扫描来自 whatsappweb 的 QR 码,我不想这样。 In my normal chrome browser I dont have to scan the QR-Code everytime.在我的普通 chrome 浏览器中,我不必每次都扫描二维码。 How can I fix this?我怎样才能解决这个问题?

Since every time you close your selenium driver/browser, the cookies that attached with the session will also be deleted.由于每次关闭 selenium 驱动程序/浏览器时,会话附带的 cookie 也将被删除。 So to restore the cookies you haved saved, you can retrieve it after the end of the session and restore it in the beginning of the next.因此,要恢复您保存的 cookie,您可以在会话结束后检索它,并在下一次开始时恢复它。

For getting the cookies,为了得到饼干,

# Go to the correct domain, i.e. your Whatsapp web
browser.get("https://www.example.com")
# get all the cookies from this domain
cookies = browser.get_cookies()
# store it somewhere, maybe a text file

For restoring the cookies用于恢复 cookie

# Go to the correct domain, i.e. your Whatsapp web
browser.get("https://www.example.com")
# get back the cookies
cookies = {‘name’ : ‘foo’, ‘value’ : ‘bar’}
browser.add_cookies(cookies)

What you could do is define a profile in Firefox. Then open firefox with that profile and open web.whatsapp.com.您可以做的是在 Firefox 中定义一个配置文件。然后使用该配置文件打开 firefox 并打开 web.whatsapp.com。 You will be prompted with the QR code.系统将提示您输入二维码。 You link that instance.你链接那个实例。 From there you can use the newly created profile in Python.从那里您可以使用 Python 中新创建的配置文件。

Creating a new profile can be done by typing about:profiles in the url section of Firefox:可以通过在 Firefox 的 url 部分键入 about:profiles 来创建新的配置文件: 在此处输入图像描述 Then open the browser by clicking 'Launch profile in new browser':然后单击“在新浏览器中启动配置文件”打开浏览器: 在此处输入图像描述

In your Python code you create a reference to this profile:在您的 Python 代码中,您创建了对此配置文件的引用:

options.add_argument('-profile')
options.add_argument('/home/odroid/Documents/PythonProfile')

A step by step guide can also be found here .也可以在此处找到分步指南。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM