如何使用 python 从 whatsapp 网页中提取二维码?

How to extract qr code from whatsapp web with python?

我尝试使用 python 和 selenium 提取二维码并且能够提取但有时无法加载二维码。

from selenium import webdriver  
from selenium.common.exceptions import NoSuchElementException  
from selenium.webdriver.common.keys import Keys  
from bs4 import BeautifulSoup

browser = webdriver.Firefox()  
browser.get('https://web.whatsapp.com/')  
html_source = browser.page_source  
browser.quit()

soup = BeautifulSoup(html_source, 'html.parser')
divs = soup.find('div', {"class":"_1pw2F"})
print(divs.attrs["data-ref"])
# in whatsapp web, qr code is the value of "data-ref" attribute of div element with class "_1pw2F"

有时 div 元素的 "data-ref" 属性值未加载。

在获取页面源之前添加延迟,因为二维码是在页面加载后异步生成的。

或者您可以定期检查QRCode部分是否存在,出现时停止检查并获取。