杨小軒
2021-10-05 22:16
采纳率: 100%
浏览 38
已结题

selenium中send_keys()方法一直报错

源码:
from keywordDemo.keyword_for_test import KeyWordDemo

kd = KeyWordDemo()

kd.visit('http://www.baidu.com')
kd.input('id', 'kw', '杨小轩')
kd.click('id', 'su')

类包:
from selenium import webdriver

class KeyWordDemo:
 driver = webdriver.Chrome()

def locator(self, loc_type, loc):
    if loc_type == 'name':
        self.driver.find_element_by_name(loc)
    elif loc_type == 'xpath':
        self.driver.find_element_by_xpath(loc)
    elif loc_type == 'id':
        self.driver.find_element_by_id(loc)
    else:
        print('元素定位错误')


def locator(self, loc):
    self.driver.find_element(*loc)

# 元素定位3.0:基于str生成元素定位

def locator(self, name, value):
    self.driver.find_element(name, value)

 def input(self, name, value, txt):
    self.locator(name, value).send_keys(txt)

# 元素的点击
def click(self, name, value):
    self.locator(name, value).click()

# 访问指定url
def visit(self, url):
    self.driver.get(url)

# 关闭浏览器,释放资源
def quit(self):
    self.driver.quit()

# 启动浏览器,创建drive对象1.0
def open_browser(self, browser_type):
    if browser_type == 'Chrome':
        self.driver = webdriver.Chrome()
    else:
        self.driver = webdriver.Firefox()
    return self.driver

# 创建driver对象2.0,基于python的反射机制
def open_browser(self, browser_type):
    driver = getattr(self, browser_type)()
    return driver

报错:
Traceback (most recent call last):
File "F:/pomdemoday1/keywordDemo/Test_Demo.py", line 7, in
kd.input('id', 'kw', '杨小轩')
File "F:\pomdemoday1\keywordDemo\keyword_for_test.py", line 31, in input
self.locator(name, value).send_keys(txt)
AttributeError: 'NoneType' object has no attribute 'send_keys'

  • 好问题 提建议
  • 收藏

1条回答 默认 最新

  • 已采纳

    你locator()方法中获取到的元素没有返回
    会默认返回None
    用return把获取到的元素返回即可

    def locator(self, loc_type, loc):
        if loc_type == 'name':
            return self.driver.find_element_by_name(loc)
        elif loc_type == 'xpath':
            return self.driver.find_element_by_xpath(loc)
        elif loc_type == 'id':
            return self.driver.find_element_by_id(loc)
        else:
            print('元素定位错误')
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题