python-3.xseleniumweb-scrapingdata-extraction

How to extract qr code from whatsapp web with python?


I have tried extracting qr code with python and selenium and able to extract but sometimes qr code is not loading.

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"

sometimes the value of "data-ref" attribute of div element is not loading.


Solution

  • Add a delay before you get the page source, as the QRCode is generated async after page load.

    Or you can periodically check if the QRCode section exist, stop the checking and get it when it appears.