为什么find_element_by_xpath()接受3个位置参数?

时间:2019-01-09 08:42:03

标签: python selenium selenium-webdriver

* args以元组形式解压缩定位符。但是我的情况是我只给出了两个参数,但是它接受了三个参数。需要帮助来理解。

我是使用python硒的新手,并且玩过github上的一些代码, 但出现错误。

TypeError:find_element_by_xpath()接受2个位置参数,但给出了3个

locator.py
from selenium.webdriver.common.by import By
class elements(object):
      Customer = (By.XPATH, "//button[contains(text(),'Customer')]")


base.py
from selenium import webdriver
from selenium.webdriver.common.by import By

class Page(object):
    def __init__(self,driver,url=None):
        self.url = url
        self.driver = driver

    def find_element_with_click(self,*locator):
        self.driver.find_element_by_xpath(*locator).click()


pages.py
from selenium import webdriver
from base import Page
from locator import *

class CustomerCreation(Page):
    def __init__(self, driver):
        self.locator = elements
        super().__init__(driver)

    def create_customer(self):
        self.driver.find_element_with_click(*self.locator.Customer)


testPages.py
import unittest
from selenium import webdriver
from pages import *
from locators import *
from selenium.webdriver.common.by import By

class TestPages(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.driver = webdriver.Chrome('C:\ChromeDriver\chromedriver')
        cls.driver.get("#server")


    def test_tes_cust(self):
        page = CustomerCreation(self.driver)
        res_page = page.create_customer()          #Getting issue at this stage

    @classmethod
    def tearDownClass(cls):
        cls.driver.close()


if __name__ == "__main__":
    suite = unittest.TestLoader().loadTestsFromTestCase(TestPages)
    unittest.TextTestRunner(verbosity=2).run(suite)

错误日志:

  

test_tes_cust(主要 .TestPages)...错误     ================================================== ====================       错误:test_tes_cust(主要 .TestPages)       -------------------------------------------------- --------------------       追溯(最近一次通话):           test_tes_cust中的文件“ testPages.py”,第28行               res_page = page.create_customer()           在create_customer中,文件“ C:\ Users ### \ PycharmProjects \ basics \ pages.py”,第35行               self.find_element_with_click(* self.locator.Customer)           在find_element_with_click中的文件“ C:\ Users ### \ PycharmProjects \ basics \ base.py”第21行               self.driver.find_element_by_xpath(* locator).click()       TypeError:find_element_by_xpath()接受2个位置参数,但给出了3个

1 个答案:

答案 0 :(得分:2)

您要再传递一个论点。您的论据是:

  1. self
  2. By.XPATH
  3. "//button[contains(text(),'Customer')]"

这就是您需要传递给find_element方法的内容。尽管find_element_by_xpath仅应接受两个参数:

  1. self
  2. "//button[contains(text(),'Customer')]"

因此,尝试将您的代码更新为

def find_element_with_click(self,*locator):
    self.driver.find_element(*locator).click()

或者您需要将Customer修改为:

Customer = "//button[contains(text(),'Customer')]"

def find_element_with_click(self, xpath):
    self.driver.find_element_by_xpath(xpath).click()