Python 3.5 Selenium XPath 语法

Python 3.5 Selenium XPath Syntax

我在 Python 3.5 中使用 Selenium 来抓取各种网站。但是,我需要从下拉列表中选择 select,但一直出现错误。我很尴尬我不能让它工作,但 XPath 对我来说是全新的所以感谢你的帮助。我的代码的截断版本是:

driver.implicitly_wait(4)
driver.find_element_by_xpath("//select[@id='ddaShowForm']/
    option[@value='Deposits']/text()").click()

我在那里等待以确保页面已完全加载,因为这是我之前遇到的问题。我得到的错误是它找不到元素。感谢您的帮助!

这是页面相关区域的片段。很抱歉格式不好。

<form id="ddaShowForm" action="https://online.wellsfargo.com/das/cgi-bin/session.cgi?sessargs=xUog_f8DdTZHif-5iVUuuwe9XQVqncvm" method="post">
<label for="transactionType">Show: &nbsp;</label>
<select id="transactionType" name="showTabDDACommand.transactionTypeFilterValue">
    <option value="All Transactions" selected="selected">All Transactions</option>
    <option value="All Transactions One Column">All Transactions in One Column</option>
    <option value="All Transactions with Balance">All Transactions with Balances</option>
    <option value="Bill Pay">Bill Pay Transactions</option>
    <option value="Check Card">Debit Card / ATM Card Transactions</option>
    <option value="Checks">Checks</option>
    <option value="Deposits">Deposits</option>
    <option value="Withdrawls">Withdrawals</option>
    <option value="transactionTypeFilter.p2p.label">WF SurePay</option>
    <option value="transactionTypeFilter.wire.label">Wires</option>
</select>
<label for="timeFilter">&nbsp;&nbsp;for&nbsp;</label>
<select id="timeFilter" name="showTabDDACommand.timeFilterValue" size="1">
    <optgroup label="" >
        <option value="3" selected="selected" >Last 90 Days</option>
        <option value="4"  >Last 6 Months</option>
        <option value="5"  >Last 12 Months</option>
        <option value="6"  >Last 18 Months</option>
        <option value="7"  >Since Last Logon</option>
        <option value="8"  >Since Last Statement</option>
        <optgroup label="--------------------" class="optgroupstyle"></optgroup>
        <option value="11"  >Date Range</option>
    </optgroup>
</select>

要从下拉列表中选择一个元素,您可以使用 Select

from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id("transactionType"))

然后您可以select使用Select

提供的任何方法
  1. select.select_by_visible_text("All Transactions")
  2. select.select_by_value("All Transactions")
  3. select.select_by_index(1)

感谢 pArAs 的帮助,我愿意为将来偶然发现此问题的任何人回答最初的 XPath 问题。他的方法向我指出 "ddaShowForm" 实际上是一种形式,而不是 'select' 元素。我原来的 XPath 的正确语法是

driver.find_element_by_xpath("//select[@id='transactionType']/
option[@value='Deposits']").click()

如果您查看 html,'select' 元素实际上具有 ID "transactionType"。我想指出的是,我还删除了末尾的“/text()”。希望对您有所帮助。