【问题标题】:Store dynamic dropdown options with Python and Selenium Webdriver使用 Python 和 Selenium Webdriver 存储动态下拉选项
【发布时间】:2015-01-12 20:00:31
【问题描述】:

我正在尝试存储由邮政编码查找生成的地址值,然后创建一个列表,我可以使用 python Random 模块使用 random.choice 选择随机值

场景:

输入邮政编码,点击“搜索” - 下拉列表会动态填充可用选项。

我正在使用字典将表单值存储为 xpath,然后使用 webdriver 到 find_elements_by_xpathfind_element_by_xpath

代码看起来像这样(格式不正确,仅供参考):

__author__ = 'scott'

from selenium import webdriver
import random

driver = webdriver.Firefox()
driver.maximize_window()
driver.get('https://www.somerandomsite')

formFields = {'postcode' : "//INPUT[@id='postcode']",
        'county' : "//SELECT[@id='address']/option"}

pcList = ['BD23 1DN', 'BD20 0JZ']

#picks a random postcode from pcList#
driver.find_element_by_xpath(formFields['postcode']).send_keys(random.choice(pcList))

driver.find_elements_by_xpath(formFields['county'])

#####now need to store the values from county and select a random option from the list######

driver.close()

在我的邮政编码上使用随机模块不是问题。

如果有人可以提供一些指导或指出我可以参考的方向,我将不胜感激 - 我只是 Selenium 和 Python 的菜鸟 - 取得了稳步进展,但似乎在这个问题上绕圈子- 我的第一个问题是使用 find_element_by_xpath 一个简单的 's' 缺少 'element' 让我有一段时间了。

【问题讨论】:

    标签: python selenium xpath selenium-webdriver webdriver


    【解决方案1】:

    使用开箱即用的 python selenium 绑定提供的Select 类 - 它是select->option HTML 结构上的一个很好的抽象层:

    from selenium.webdriver.support.ui import Select
    
    # initialize the select instance
    select = Select(driver.find_element_by_id('address'))
    
    # get the list of options and choose a random one
    options = [o.text for o in select.options]
    option = random.choice(options)
    
    # select it
    select.select_by_visible_text(option)
    

    【讨论】:

    • 谢谢alecxe。正是我要找的东西。真的很感激。
    猜你喜欢
    • 2018-08-10
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    相关资源
    最近更新 更多