【问题标题】:how to retrieve data from dynamic table - selenium python如何从动态表中检索数据 - selenium python
【发布时间】:2018-05-23 09:44:51
【问题描述】:

我正在尝试从 selenium python 中的动态 web 表中检索数据,但控制台中的错误为 错误为“

values = self.driver.find_element_by_xpath(".//*[@id='table01']/tbody/tr["+row+"]/td["+col+"]").text

TypeError: 必须是 str,而不是 int

失败(错误=1)

class DynamicWebTable1(unittest.TestCase):


@classmethod
def setUpClass(cls):
    chrome_driver_path = os.path.abspath('..')  + "\\Drivers\\chromedriver.exe"

    cls.driver=webdriver.Chrome(chrome_driver_path)

    cls.driver.implicitly_wait(30)
    cls.driver.maximize_window()
    # navigate to the application home page
    cls.driver.get("http://qavalidation.com/demo/")

def test_get_table_data(self):
    time.sleep(10)
    columns = len(self.driver.find_elements_by_xpath(".//*[@id='table01']/tbody/tr[1]/td"))
    rows = len(self.driver.find_elements_by_xpath(".//*[@id='table01']/tbody/tr"))
    print("rows - ",rows)   # rows -  3
    print("columns - ",columns) #columns -  4

    for row in range(rows):
        for col in range(columns):
            values = self.driver.find_element_by_xpath(".//*[@id='table01']/tbody/tr["+row+"]/td["+col+"]").text
            print(" Dynamic web table index {row} ,{col} value is {values} ".format(row, col, values))

@classmethod
def tearDownClass(cls):
    # close the browser window
    cls.driver.quit()

Github 示例代码https://github.com/venkywarriors619/selenium_with_python/blob/master/Python_basics/SeleniumWebDriver_Advanced/DynamicWebTable1.py

动态我们来自http://qavalidation.com/demo/

【问题讨论】:

  • 试试values = self.driver.find_element_by_xpath(".//*[@id='table01']/tbody/tr[%s]/td[%s]" % (row, col)).text

标签: python python-3.x selenium selenium-webdriver xpath


【解决方案1】:

此错误消息...

TypeError: must be str, not int

...暗示在上述行中,您的程序需要一个 String 类型的参数,而 Interger 类型的参数被传递给它。

要从动态 web 表中检索数据,您需要更改以下代码行:

for row in range(rows):
    for col in range(columns):
        values = self.driver.find_element_by_xpath('.//*[@id="table01"]/tbody/tr["'+row+'"]/td["'+col+'"]').text

【讨论】:

  • 请更新您的答案,因为它会导致语法错误。正确的语法是 +"'col'"+ 。第一个双引号 ",在 ' 之后,在 col 之后,在 ' 之后,在双引号 " 之后。
【解决方案2】:

你不能添加字符串和整数:

>>> "1"+2
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    "1"+2
TypeError: must be str, not int

您必须将 int 转换为 str :

>>> "1"+str(2)
'12'

【讨论】:

    【解决方案3】:

    它需要字符串值,但您传递的是 int 值。当我们将字符串连接到整数时会发生这种情况。请更改代码中的以下行。

    values = self.driver.find_element_by_xpath(".//*[@id='table01']/tbody/tr["+row+"]/td["+col+"]").text
    

    values = self.driver.find_element_by_xpath(".//*[@id='table01']/tbody/tr["+str(row)+"]/td["+str(col)+"]").text
    

    它可能会解决您的问题。

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      相关资源
      最近更新 更多