python - 使用 selenium 从具有相同 xpath 的多个选择中选择下拉值
问题描述
我正在尝试通过 python 从这个电子商务网站上抓取数据
因为它需要首先选择运输位置才能访问数据,并且 3 个选择具有相同的 xpath,所以我使用下面的代码
city = browser.find_element(By.XPATH,"(//select[not(@id) and not(@class)])[1]")
citydd = Select(city)
citydd.select_by_value('01') # Hanoi
time.sleep(1)
district = browser.find_element(By.XPATH,"(//select[not(@id) and not (@class)])[2]")
districtdd = Select(district)
districtdd.select_by_value('0101') # Ba Dinh
time.sleep(1)
ward = browser.find_element(By.XPATH,"(//select[not(@id) and not (@class)])[3]")
warddd = Select(ward)
warddd.select_by_value('010104') # Cong Vi
browser.find_element(By.XPATH,"//div[text()='Xác nhận']").click() # Xac nhan
它返回给我这个错误
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"(//select[not(@id) and not(@class)])[1]"}
我可以知道如何绕过这种情况吗?
解决方案
这是我尝试过的 -
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.wait import WebDriverWait
from time import sleep
from selenium import webdriver
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get('https://vinmart.com/')
FirstDropDown = Select(driver.find_element_by_xpath("(//select)[1]"))
FirstDropDown.select_by_index(1)
sleep(2)
SecondDropDown = Select(driver.find_element_by_xpath("(//select)[2]"))
SecondDropDown.select_by_index(1)
sleep(2)
ThirdDropDown = Select(driver.find_element_by_xpath("(//select)[3]"))
ThirdDropDown.select_by_index(1)
我使用过sleep()
是因为根据之前的下拉选择填充下拉列表中的数据需要时间。
如果它解决了您的问题,请将其标记为答案。
推荐阅读
- vue.js - 在 vuetify 数据表上导出到 excel
- varnish - 无法从 nginx/varnish 获取 real-ip 传递,总是显示 127.0.0.1
- google-cloud-platform - DAG 不接受参数化消息
- android - 这到底是什么,它,在 kotlin android 中的活动?
- python - 使用 pandas 根据现有列值向数据框添加新列
- javascript - 即使文件不需要承诺,JavaScript 也会等待异步文件完成
- powershell - 如何返回嵌套数组的顶级父数组名称?
- apache-kafka - KStream 因“无法创建内部主题”而失败
- swift - 旋转时详细视图控制器的 UISplitViewController 默认对象
- android - 请求模型应该推断无效吗?