计算网页中tag_name的数量(python,selenium)

时间:2016-06-29 19:30:19

标签: python html selenium xpath webpage

您有以下代码:

for each in driver.find_elements_by_xpath(".//*[@id='ip_market" + market + "']/table/tbody")
    cell = each.find_elements_by_tag_name('td')[0]
    cell2 = each.find_elements_by_tag_name('td')[1]
    cell3 = each.find_elements_by_tag_name('td')[2]

我的问题是,我不知道每个td内有多少each(有时3个,有时15个等等......)。

是否有可能检查tdfor each的数量,以便制作动态find_elements_by_tag_name('td')

3 个答案:

答案 0 :(得分:0)

只是不要通过索引获取它们,使用:

cells = each.find_elements_by_tag_name('td')

然后cells将是元素列表,您可以在其上调用len()

print(len(cells))

或切片:

cells[:3]  # gives first 3 elements
cell1, cell2, cell3 = cells[:3]  # unpacking into separate variables

或者,您可以获取每个单元格的文本:

[cell.text for cell in cells]

答案 1 :(得分:0)

find_elements_by_tag_name返回一个列表。使用该列表上的len()来获取该标记名称的元素数量。此外,不是说for each我会轻轻地建议使用更具描述性的作业。

table = driver.find_element_by_xpath(".//*[@id='ip_market" + market + "']/table/tbody")
table_rows = table.find_elements_by_tag_name("tr")
for row in table_rows:
    row_cells = row.find_elements_by_tag_name("td")
    num_of_cells = len(row_cells)

答案 2 :(得分:0)

通过阅读你的评论,看起来这就是你想要做的......

for each in driver.find_elements_by_xpath(".//*[@id='ip_market" + market + "']/table/tbody")
    for i in range(0,len(each.find_elements_by_tag_name('td'))
        // you can now use i as an index into the loop through the TDs
        print "do something interesting with i: " + i