【问题标题】:Selecting an item from a dropdown menu with Selenium and python使用 Selenium 和 python 从下拉菜单中选择一个项目
【发布时间】:2021-12-08 04:35:39
【问题描述】:

我正在尝试开发一个“机器人”,以便在“zalando”网站上更快地进行购买。 例如,假设我想买这个:https://www.zalando.it/nike-sportswear-air-force-1-07-lv8-sneakers-basse-whiteblackwolf-grey-ni112o0m9-a11.html

我需要一个代码来从菜单中选择鞋码(查看链接或下图),我尝试了“选择”功能:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
from selenium.webdriver.support.ui import Select
 #The first thing you’ll want to do with WebDriver is navigate to a link.
#The normal way to do this is by calling get method:

options = Options()
ua = UserAgent()
userAgent = ua.random
print(userAgent)
options.add_argument(f'user-agent={userAgent}')

driver = webdriver.Chrome(options=options)
driver.get("https://www.zalando.it/nike-sportswear-air-force-1-07-lv8-sneakers-basse- 
whiteblackwolf-grey-ni112o0m9-a11.html")

#tried this
element = driver.find_element_by_xpath('/html/body/div[7]/div/div[3]')
all_options = element.find_elements_by_tag_name("_7Cm1F9 ka2E9k uMhVZi dgII7d _6yVObe 
pVrzNP")
for option in all_options:
  print("Value is: %s" % option.get_attribute("value"))
  option.click()

#and this:

#select = Select(driver.find_element_by_id('id'))
#select.deselect_all()

element = 
driver.find_element_by_xpath('/html/body/div[2]/div/div[1]/div/div/div[2]/div[1]/x- 
wrapper-re-1-6/div/div[2]').click

但是 Select 不起作用,我希望有人能解释一下原因。谢谢!

【问题讨论】:

    标签: python selenium selenium-webdriver bots


    【解决方案1】:

    此网页的结构相当复杂,实际上并没有像您预期的那样使用select 元素。

    我总是先在开发者控制台的 Elements 选项卡中查看实际的 html 结构,尺寸选择如下所示:

    原则上您必须执行以下 3 个步骤:

    找到打开尺寸选择的元素

    这似乎是通过带有 id picker-trigger 的 button 完成的,并且应该只使用:

    buttonElement = driver.find_element_by_id('picker-trigger')
    buttonElement.click()
    

    在尺码表的表格框内找到合适的尺码

    可以使用名称为size-picker-form 的表单和使用带有特定文本的跨度的大小行来标识表本身:

    sizeElement = driver.find_element_by_xpath('//form[@name="size-picker-form"]//span[text()="40"]')
    sizeElement.click()
    

    我希望这可以帮助或至少为您指明正确的方向。

    【讨论】:

    • 谢谢!除了尺寸选择外,它可以工作......这是错误:selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//span[@value='43']"}
    • @LuigiV。我已经简化了 xpath 定位器并将其分组为一个块。如果它仍然不起作用,则可能与时间有关,您可能希望在选择大小之前添加sleep 命令或(实际上正确的方法= 开始使用WebDriverWait 。
    • @LuigiV。你看到我原来的答案的变化了吗?他们在工作吗?
    猜你喜欢
    • 2022-01-23
    • 2020-09-17
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2018-02-17
    • 2020-09-01
    • 2019-02-04
    • 1970-01-01
    相关资源
    最近更新 更多