【问题标题】:How to webscrape a popup on a new page with selenium?如何使用硒在新页面上抓取弹出窗口?
【发布时间】:2021-07-21 05:40:39
【问题描述】:

我想知道如何使用 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")

【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

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

    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)
    

    打印:

    SIGNUP15
    

    【讨论】:

    • 非常好的方法,我必须学习它;)但他询问了 Selenium 方法
    • @Prophet 好吧,他可以用 selenium 加载这个 URL....但是.... ;)
    • 再一次,我看到这种方式有多好。我确实想在最近的将来学习这个。但他正在做的方式(甚至可能不知道这种方法)是传统的 Selenium。
    • 感谢您的帮助。 BS更容易:)
    【解决方案2】:

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

    Whandles = driver.window_handles
    print(Whandles)
    

    并且应该清楚您的新窗口的窗口句柄是什么。然后就可以了

    driver.switch_to_window_(desiredWindowHandle)
    

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

    【讨论】:

      【解决方案3】:

      点击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()会打开一个新标签。
      现在您必须使用 driver.switch_to.window(driver.window_handles[-1]) 将驱动程序切换到新选项卡
      在新选项卡上时,您可以从位于 //div[@class='coupon-code'] xpath
      的元素中获取文本 现在您可以通过driver.close关闭新打开的选项卡
      并通过driver.switch_to.window(driver.window_handles[0]) 切换回上一个选项卡 查看更多详情here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多