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

2024-04-20 09:02:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码是:

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或名称,而是一个值。 那么,如何更改对象的值呢?
比如,改变它的值,然后从下拉列表的选项中选择一个选项?在


Tags: thefromimportsupporttime选项driverselenium
3条回答

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

select元素内部将是一组option元素。在

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

使用浏览器中的web开发工具查看下拉列表的html代码,并检查是否存在这种情况。在

要设置其值,只需按照用户的操作:

  1. 单击select元素
  2. 单击要选取的option元素。在

有多种方法可以找到option元素。 如果您想通过可见文本来识别它,请使用@MarkRowlands answer。 如果您想通过它的值来定位它,可以使用css选择器,如option[value='valueToPick']。在

您可以按标记名iterate through the elements并以这种方式选择一个选项,也可以使用它们的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()

关于how to do it in Java有一个非常相似的问题。在

xpath method在Python中:

^{pr2}$

如果要与<select>元素交互,请使用Select()类。在

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

相关问题 更多 >