为什么无法使用selenium对文本框"send_keys"?AttributeError: 'NoneType

1 投票
1 回答
11270 浏览
提问于 2025-04-17 23:20

我在这个网站上填写文本框时遇到了很大的困难。这个元素的类型是"type='text'"。它总是返回一个错误,提示AttributeError: 'NoneType'。

我用一个try语句来检查它是否真的被点击了,结果没有出错。而且,文本框是被选中的,当我把它放在前面窗口时,错误发生后我可以在文本框里输入内容,而不需要再点击其他东西。

我尝试把点击前的暂停时间延长到1分钟,但没有任何效果。

我尝试用xpath选择元素,结果也是一样。

我尝试点击这个对象,暂停10秒,然后再点击一次。还是没有任何反应。

我的代码:

def Search(driver,productID):
    print "Initiate Search"

    #Fill in current product ID
    #/html/body/table[3]/tbody/tr/td/table/tbody/tr/td[2]/div[2]/form/table/tbody/tr/td/input

    try: inputElement = driver.find_element_by_name("CategoryName").click()
    except: print "could not click"
    print "Clicked Product ID"

    time.sleep(5)
    inputElement.send_keys(str(productID))  ##Line 105 - Errors out here

错误信息

Traceback (most recent call last):
  File "/Users/ME/Documents/PYTHON/Creating Static Attributes/StaticWAttributes_1.py", line 246, in <module>
    Search(driver,productID)
  File "/Users/ME/Documents/PYTHON/Creating Static Attributes/StaticWAttributes_1.py", line 105, in Search
    inputElement.send_keys(str(productID))
  AttributeError: 'NoneType' object has no attribute 'send_keys'

最后的输出打印语句:

Initiate Search
Clicked Product ID

HTML代码:

  <table cellSpacing="0" cellPadding="0" border="0">
        <tr>
          <td class="actionrow">Search Products by  
          <select name="categorytype">
                        <option selected value="name">Product Name or Description</option>
                        <option  value="catid">Product ID</option>
                  </select> <input type="text" name="CategoryName" value="" size="20"><? <<-- I AM TRYING TO CLICK THIS ?>
                  &nbsp;in&nbsp;
                  <select name="ddlproductType" ID="Select2">
                    <option selected value="100">All</option>
                        <option  value="1">Versioned</option>

                            <option  value="7">Variable</option>

                        <option  value="5">Static with Attributes</option>
            <option  value="11">PowerPoint</option>
                  </select>&nbsp;
                <input type="submit" value="Go" name="action" onClick="javascript:resetAll();"> 
          </td>
        </tr>
  </table>

1 个回答

9

你的问题出在这里:

    try: inputElement = driver.find_element_by_name("CategoryName").click()

我不太确定在Python中inputElement是什么,但我猜它可能还是空值。我觉得click()这个方法不会返回任何东西。

如果你把它改成这样,应该就能正常工作了:

try: inputElement = driver.find_element_by_name("CategoryName")
    inputElement.click()

撰写回答