小编典典

使用Selenium和Python列出选择选项值

selenium

我有以下HTML代码

<select name="countries" class_id="countries">
    <option value="-1">--SELECT COUNTRY--</option>
    <option value="459">New Zealand</option>
    <option value="100">USA</option>
    <option value="300">UK</option>
</select>

我正在尝试使用Selenium获取选项值的列表(例如459、100等,而不是文本)。

目前,我有以下Python代码

from selenium import webdriver

def country_values(website_url):
    browser = webdriver.Firefox()
    browser.get(website_url)
    html_code=browser.find_elements_by_xpath("//select[@name='countries']")[0].get_attribute("innerHTML")
    return html_code

如您所见,代码返回纯HTML,我正在使用HTMLParser库进行解析。有什么方法可以仅使用Selenium来获取选项值?换句话说,不必解析Selenium的结果吗?


阅读 322

收藏
2020-06-26

共1个答案

小编典典

检查一下,这是我做的,然后才知道选择模块做了什么

from selenium import webdriver

browser = webdriver.Firefox()
#code to get you to the page

select_box = browser.find_element_by_name("countries") 
# if your select_box has a name.. why use xpath?..... 
# this step could use either xpath or name, but name is sooo much easier.

options = [x for x in select_box.find_elements_by_tag_name("option")]
# this part is cool, because it searches the elements contained inside of select_box 
# and then adds them to the list options if they have the tag name "options"

for element in options:
    print element.get_attribute("value") 
    # or append to list or whatever you want here

这样的输出

-1
459
100
300
2020-06-26