-1

I would like to know how to webscrape a popup on a new page with selenium (or another framework). The Python code below clicks on a button then a new page opens but I don't know to copy/paste the promo code. Can you help ?

from selenium import webdriver
from time import sleep
from selenium.webdriver import ChromeOptions, Chrome




class Coupons_offers:



def stayOpen(self):
    opts = ChromeOptions()
    opts.add_experimental_option("detach", True)
    driver = Chrome(chrome_options=opts)

def __init__(self):
    self.driver = webdriver.Chrome()
    self.driver.get("https://www.offers.com/scotch-porter/")
    sleep(2)
    self.driver.find_element_by_xpath('//button[@id="_evidon-banner-acceptbutton"]').click()
    sleep(2)
    self.driver.find_element_by_xpath('//body/div[@id="main"]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/a[1]').click()
    sleep(4)
    self.driver.get("https://www.offers.com/scotch-porter/#offer_id=4467763")
Yo'python
  • 11
  • 4

3 Answers3

2

The modal window is loaded from external URL. You can use this code how to parse the coupon code (just replace the offerid for ID what you want):

import requests
from bs4 import BeautifulSoup

url = "https://www.offers.com/exit/modal/offerid/4467763/"  # <-- replace offerid here

soup = BeautifulSoup(requests.get(url).content, "html.parser")
print(soup.find(class_="coupon-code").text)

Prints:

SIGNUP15
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

By clicking self.driver.find_element_by_xpath('//body/div[@id="main"]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/a[1]').click() a new tab is opened.
Now you have to switch driver to the new tab with driver.switch_to.window(driver.window_handles[-1])
When on the new tab you can get the text from element located by //div[@class='coupon-code'] xpath
Now you can close the new opened tab by driver.close
And switch back to the previous tab by driver.switch_to.window(driver.window_handles[0]) See more details here

Prophet
  • 32,350
  • 22
  • 54
  • 79
0

It sounds like you will probably need to get the window handle of the new window and go to it. To debug, try

Whandles = driver.window_handles
print(Whandles)

And it should be clear what the window handle is for your new window. Then you can do

driver.switch_to_window_(desiredWindowHandle)

before proceeding with code to use the new window.

C. Peck
  • 3,641
  • 3
  • 19
  • 36