使用Selenium的Python API - 如何获取表格中的行数?

1 投票
2 回答
3170 浏览
提问于 2025-04-16 11:15

我该如何使用Selenium的Python接口获取HTML表格中的行数呢?

我有一个包含“键”和“值”两列的表格,我想把它读入一个字典里。大概是这样的:

browser = Selenium(...)
...
rows = ? (this is what I need)
for r = range(row):
    key = browser.get_table('tablename.' + r + '.0')
    value = browser.get_table('tablename.' + r + '.1')
    my_dict[key] = value

谢谢,

杰米

2 个回答

0

这是我目前的解决办法:

row = 0
while browser.is_element_present('//tablename//tr[' + str(row+1) + ']/td[1]'):
    key = browser.get_table('tablename.' + str(row) + '.0')
    value = browser.get_table('tablename.' + str(row) + '.1')
    my_dict[key] = value
    row = row + 1

请注意,在is_element_present()这个方法中,行和列的编号是从1开始的,而在get_table()这个方法中,行和列的编号是从0开始的。

2

来自驱动程序的内容:

def get_xpath_count(self,xpath):
    """
    Returns the number of nodes that match the specified xpath, eg. "//table" would give
    the number of tables.

    'xpath' is the xpath expression to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you.
    """
    return self.get_number("getXpathCount", [xpath,])

撰写回答