首页 > 解决方案 > 更改选择框 Selenium 的值

问题描述

选项 1 自动从等于 10 的 HTML 中选择。

这是 HTML:

<form>
<table>
    <tr>
        <th>Name:</th>
        <td><input id="search_term" /></td>
    </tr>
    <tr>
        <th>Page size:</th>
        <td>
            <select id="page_size">
                <option>4</option>
                <option selected>10</option>
                <option>20</option>
            </select>
        </td>
    </tr>
    <tr>
        <td></td>
        <td>
            <input type="submit" id="search" value="Search" />
        </td>
    </tr>
</table>
</form>

我尝试运行:

js = "document.getElementById('page_size').options[1].text ='1000';"
# js = "document.getElementById('page_size').options[1].text ='1000'"
driver.execute(js)

KeyError我执行时得到js。所以我尝试用 Python 的方式来做,但是没有任何反应:

x = driver.find_element_by_xpath('//*[@id="page_size"]/option[2]')
x.clear()
x.send_keys(1000)

这是我在链接上测试的链接

1书中关于如何做的描述' http ://example.webscraping.com/places/default/search '

标签: pythonselenium

解决方案


当您想更改选项元素文本时,我刚刚使用 jsfiddle 测试了这段 javascript 并且它可以工作,尝试使用“innerText”而不是“text”:

document.getElementById('page_size').options[1].innerText = "1000";

链接到 jsfiddle:https ://jsfiddle.net/z1omaue3/


推荐阅读