Python 如何使用selenium在新页面上弹出窗口?

Python 如何使用selenium在新页面上弹出窗口?,python,selenium,web-scraping,Python,Selenium,Web Scraping,我想知道如何使用selenium(或其他框架)在新页面上弹出一个弹出窗口。 下面的Python代码单击一个按钮,然后打开一个新页面,但我不知道如何复制/粘贴促销代码。你能帮忙吗 from selenium import webdriver from time import sleep from selenium.webdriver import ChromeOptions, Chrome class Coupons_offers: def stayOpen(self): o

我想知道如何使用selenium(或其他框架)在新页面上弹出一个弹出窗口。 下面的Python代码单击一个按钮,然后打开一个新页面,但我不知道如何复制/粘贴促销代码。你能帮忙吗

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")

单击
self.driver。通过xpath('//body/div[@id=“main”]/div[1]/div[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[1]/a[1]”查找元素。单击()
打开一个新选项卡。
现在,您必须使用
driver.switch\u to.window(driver.window\u句柄[-1])将driver切换到新选项卡。

在新选项卡上,您可以从位于
//div[@class='优惠券-code']
xpath

的元素中获取文本 现在,您可以通过
驱动程序关闭新打开的选项卡。关闭

然后通过
driver.switch\u to.window(driver.window\u句柄[0])切换回上一个选项卡

查看更多详细信息

听起来您可能需要获取新窗口的窗口句柄并转到它。要调试,请尝试

Whandles = driver.window_handles
print(Whandles)
而且应该清楚新窗口的窗口句柄是什么。那你就可以了

driver.switch_to_window_(desiredWindowHandle)

在继续使用新窗口的代码之前。

模式窗口是从外部URL加载的。您可以使用此代码解析优惠券代码(只需替换您想要的ID的offerid):


非常好的方法,我必须学习;)但他问硒的问题approach@Prophet嗯,他可以用selenium加载这个URL……但是……)再一次,我看到这种方式有多好。我确实想在最近的将来了解这一点。但是他现在的做法(甚至可能不知道这种方法)是一种传统的Selenium。谢谢你的帮助。使用BS更容易:)
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)