python - 查找并单击脚本元素内的元素
问题描述
我正在尝试使用 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()
解决方案
关闭 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
。
推荐阅读
- javascript - javascript中的文档是什么?
- php - 无法在实体 A 到 B 之间添加新的 ManyToMany 属性,因为我已经有一个包含这两个实体的 ManyToMany 属性
- flutter - 如何根据每个屏幕尺寸调整我的颤振应用程序的大小?
- c# - 无效的对象名称 dbo.EdmMetaData 调用新的 EFObjectSpaceProvider
- content-security-policy - 外部脚本的内容安全策略问题
- python - 在数组列上查找共同的朋友/互动
- spring - 我应该在 API 响应中包含嵌套数据还是发出两个单独的请求?
- java - 编写一个程序,要求用户输入金额并将其转换为越南盾
- javascript - 我无法理解这个 TabBarCustomButton 函数结构的部分内容,谁能解释一下?
- python - 使用时出现AttributeError;在 IBM Cloud Notebook 中插入代码 pandas DataFrame。该怎么办?