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

标签 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 的结果?

最佳答案

检查一下,这是我在知道选择模块做了什么之前是怎么做的

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

关于python - 使用 Selenium 和 Python 列出选择选项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18515692/

相关文章:

python - 如何使用 Python 将函数应用于列表中的元素对?

python - 两个图像之间重叠标签的计数 - Python/NumPy

python - 错误 : Argument must be a dense tensor: range(2, 3) - 得到形状 [1],但想要 []

java - ios - appium 无法从下往上滑动

python - 如何切片 2D numpy 数组以获得它的直接邻居?

python - 关闭由 ConfigParser 打开的文件

c# - 在 selenium 中导航 url 期间停止页面加载

selenium - 无法访问 PHPUnit Coverage 中的 PHPUNIT_SELENIUM_TEST_ID cookie

ruby - 在 selenium webdriver 中使用 phantomjs 代理

selenium - 未捕获的 DOMException : Failed to execute '$' on 'CommandLineAPI' : not a valid selector