如何通过Selenium更改对象值(HTML代码中的元素)?

-1 投票
3 回答
645 浏览
提问于 2025-04-28 14:07

这是我的代码:

import threading
import Queue
import socket
import pickle
import base64
import time

def enter_mashov():
    from selenium import webdriver
    from selenium.common.exceptions import TimeoutException
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC 

    # Create a new instance of the Firefox driver
    start = time.time()
    driver = webdriver.Firefox()

    driver.get('https://safe.mashov.info/students/login.aspx')

    # find the elements
    IDChanger = driver.find_element_by_id('TextBoxId')
    PassChanger = driver.find_element_by_id('TextBoxPass')

    IDChanger.send_keys('someid')
    PassChanger.send_keys('somepass')

enter_mashov()

我想做的事情和我之前做的ID更改器和密码更改器一样,但问题是,这里是一个下拉列表,它的选项没有ID或名字,只有一个值。那我该怎么改变一个对象的值呢?
比如说,怎么通过改变它的值来选择下拉列表中的一个选项呢?

暂无标签

3 个回答

0

如果你想和一个 <select> 元素进行互动,可以使用 Select() 这个类。

select = Select(driver.find_element_by_id("select_id"))
select.select_by_visible_text("The thing you want to select")
0

你可以通过标签名来遍历这些元素,然后选择你想要的选项,或者你也可以使用它们的xpath,这样就不需要元素有一个id了:

select = driver.find_element_by_tag_name("select")
allOptions = select.find_elements_by_tag_name("option")
for option in allOptions:
    print "Value is: " + option.get_attribute("value")
    option.click()

还有一个非常相似的问题,关于如何在Java中做到这一点

在Python中使用xpath方法

from selenium.webdriver.common.by import By
inputs = driver.find_elements(By.XPATH, "//input")
0

下拉列表很可能是一个 select 元素。

在这个 select 元素里面,会有一组 option 元素。

<select...>
    <option value="valueForFirstOption"...>Visible text for first option</option>
    <option value="valueForSecondOption"...>Visible text for second option</option>
</select>

你可以使用浏览器中的网页开发者工具,查看下拉列表的 HTML 代码,确认这一点。

要设置它的值,就像用户操作一样:

  1. 点击 select 元素
  2. 点击你想选择的 option 元素。

有多种方法可以找到这个选项元素。如果你想通过可见的文字来识别它,可以参考 @MarkRowlands 的回答。如果你想通过它的值来定位,可以使用类似 option[value='valueToPick'] 的 CSS 选择器。

撰写回答