首页 > 解决方案 > 查找并单击脚本元素内的元素

问题描述

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

标签: pythonselenium

解决方案


关闭 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 - 下拉菜单选项值

你有父母的 id select: geolocation-popup-select-market


推荐阅读