【问题标题】:Find and click an element inside a script element查找并单击脚本元素内的元素
【发布时间】:2021-06-07 18:36:01
【问题描述】:

我正在尝试使用 python 和 selenium 更改网站上的商店位置。 来自 Firefox 的 Selenium IDE 插件给了我一个序列。该序列在 Firefox 的 selenium IDE 中工作,但我无法让它在 Python (Spyder) 中工作。我要单击的元素在脚本内,没有工具可以在脚本内找到元素。 Beautifulsoup 做不到,selenium 也做不到。 使用以下代码,我尝试在每个商店中获取产品价格,因此我需要将商店(它是左上角的黄色按钮,然后是下拉列表)更改为下拉列表中的每个商店并 scrape 产品价格的页面来源。但是每当我尝试“driver.find_element_by_”时,我都会得到“无法找到元素:”

点击序列是使用 Firefox 的 Selenium IDE 插件记录的。 或者也许有比 selenium 更快的方法在商店之间切换并获得产品价格。我不能只用 Beautifulsoup。

from selenium import webdriver
driver = webdriver.Firefox(executable_path='d:\Work\geckodriver.exe')
url = 'https://www.castorama.pl/deska-14x90x540-eslov-jodel-1-94-id-1105153.html'
driver.get(url)
driver.maximize_window()
driver.find_element_by_id("market-name").click() #Unable to locate element
driver.find_element_by_id("shop-selection-master-infostore").click()
driver.find_element_by_xpath("//div[@id='geolocation_popup_select_market_chosen']/a/span").click()
driver.find_element_by_xpath("//div[@id='geolocation_popup_select_market_chosen']/div/ul/li[2]").click()

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    关闭 cookie 栏:

    from selenium import webdriver
    
    driver = webdriver.Firefox(executable_path='d:\Work\geckodriver.exe')
    url = 'https://www.castorama.pl/deska-14x90x540-eslov-jodel-1-94-id-1105153.html'
    driver.get(url)
    driver.maximize_window()
    driver.find_element_by_css_selector('[onclick="bold.cookie.closeCookie();"]').click()
    driver.find_element_by_id('shop-selection-master').click()
    

    纯粹主义者不会喜欢它,但你也可以使用 javascript

    driver.execute_script("document.querySelector('#shop-selection-master').click();")
    

    这里详细介绍了选择选项:Selenium - Python - drop-down menu option value

    你有父select的ID:geolocation-popup-select-market

    【讨论】:

    • 关闭 cookie 栏后,行 driver.find_element_by_id('shop-selection-master').click() 仍然无法找到元素。但是,“driver.execute_script”可以解决问题并弹出弹出窗口。我用 "driver.switch_to.active_element; driver.find_element_by_xpath("//div[@id='geolocation_popup_select_market_chosen']/a/span").click();driver.find_element_by_xpath("//div[@id ='geolocation_popup_select_market_chosen']/div/ul/li[5]").click()".然后,页面将自身配置为所选商店,然后我无法切换到默认内容。
    • 你可能每次都需要循环设置store
    • 可以用PyQt来选择商店(执行脚本)然后报废网页内容吗?硒非常缓慢。
    猜你喜欢
    • 2020-03-14
    • 1970-01-01
    • 2021-09-12
    • 2017-07-09
    • 2014-10-11
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多