Chrome 在Python中使用selenium库无法在弹出消息中定位x按钮

vsaztqbk  于 2023-04-27  发布在  Go
关注(0)|答案(2)|浏览(172)

在下面提到的网站上,当我使用chromedriver和try-except块中的extract_data()函数打开它时,我试图通过单击“x”按钮来关闭弹出消息。但是,它单击了错误的按钮。
有趣的是,当我在调试模式下,在try块中带有变量close_button的行上放置一个断点,并手动等待弹出消息出现在浏览器中,然后运行下一行,它正确地识别了'x'按钮并正确地消除了消息。
我很难解决这个问题,这样我的程序就可以正确地识别和关闭'x'按钮,而不是其他标签为'button'的标签。我已经尝试过使用By.TAG_NAME进行特定操作,但使用其他方法(如By.ID,By.CLASS_NAME,By.CSS_SELECTOR等)多次尝试都失败了。

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import PySimpleGUI as sg
from pathlib import Path
import pandas as pd

url = r"https://simpletire.com/brands/american-tourer-tires/touring-a-s#badge=Best%20rated&curationPos=none&curationSeq=none&curationSource=none&delivery=Del3&itemId=208786&mpn=AMSYTH0258&pageSource=PDP&pick=best-rated&productPos=none&rad=BE&region=r2&tireSize=195-55r15&userRegion=2&userZip=19422&v=1&zip=19422"
service = r"somefilepath"
filename = "simple_tire_data"

def extract_data(url, service, output_folder, filename):
    """Main function for extracting data from simpletire.com and exporting to excel.
    
    Parameters:
    url -- the url of the page with the drop-down list of tire options
    service -- the absolute folder path to your chromedriver.exe on your PC. Please ensure you have the version downloaded
    that matches your chrome web browser version. You can download the chromedriver.exe from
    this site: https://chromedriver.chromium.org/downloads
    output_folder -- the folder where you want to store the output excel file
    filename -- the name of the output excel file
    """
    # use selenium to open URL with chrome driver
    driver = get_driver(url, service)
    
    # wait for pop-up to appear
    WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, "//*[@id='attentive_overlay']")))
    
    # find and click "X" button to close pop-up
    try:
        close_button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.TAG_NAME, "button")))
        actions = ActionChains(driver)
        actions.move_to_element(close_button).click().perform()
    except:
        print("Pop up message was not able to be dismissed.")

    # find the dropdown list and loop through the options
    dropdown = driver.find_element(By.XPATH, "//*[@id='selectSizeButton']")
    options = dropdown.find_elements(By.TAG_NAME, "span")
    
    tire_data = {}

    # for option in options:
    #     option_text = option.text
    #     option.click()
        
    #     # get data from tech specs container
    #     tech_specs_data = scrape_tech_specs_data(driver)

    #     # store data in nested dictionary
    #     tire_data[option_text] = tech_specs_data
    
    # print(tire_data)

    # driver.quit()

    # # convert dictionary to dataframe
    # df = pd.DataFrame.from_dict(tire_data, orient="index")

    # # export dataframe to excel
    # output_path = Path(output_folder, f"{filename}.xlsx")
    # df.to_excel(output_path, index=True)

def get_driver(url, service):
    chrome_options = Options()
    chrome_options.add_experimental_option("detach", True)
    service = Service(rf"{service}")
    chrome_browser = webdriver.Chrome(service=service, options=chrome_options)
    chrome_browser.get(rf"{url}")
    chrome_browser.maximize_window()

    return chrome_browser

extract_data(url, service, output_folder, filename)

附件是HTML的屏幕截图:

w46czmvw

w46czmvw1#

我看到一个IFRAME,其中这个关闭按钮元素被 Package 。尝试先切换到IFRAME,使用下面的代码:

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"attentive_creative")))

之后,尝试单击关闭按钮,使用Jeff C提供的代码/定位器:

close_button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "closeIconContainer")))
close_button.click()

关闭弹出窗口后,不要忘记切换回主要内容,使用以下代码:

driver.switch_to.parent_frame()
zzlelutf

zzlelutf2#

BUTTON在许多网页上都很常见。您需要使用更具体的定位器,以便您可以找到该BUTTON,并且只有该BUTTON是唯一的。在创建定位器时,我们正在寻找元素的独特之处。有时您会找到idname属性。这些通常是最佳候选者。在这种情况下,从您发布的HTML中,我们可以看到您试图单击的按钮有一个ID。因此,将简单的定位器更改为下面应该可以工作。

close_button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "closeIconContainer")))

相关问题