首页 > 解决方案 > 使用 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]"}

我可以知道如何绕过这种情况吗?

标签: pythonseleniumweb-scrapingxpath

解决方案


这是我尝试过的 -

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()是因为根据之前的下拉选择填充下拉列表中的数据需要时间。

如果它解决了您的问题,请将其标记为答案。


推荐阅读