2016-06-29 200 views
-1

喜有以下代码:数号码(蟒蛇,硒)

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等等)。

是否有可能检查for each内部的td s的编号以使动态find_elements_by_tag_name('td')

回答

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] 
+0

谢谢您的回答! :)我的问题是,我需要的索引,以便在我的SQL数据库中正确插入数据,否则我不知道如何插入它们...对不起,但我是新的Python和SQL ...但如果你有更好的解决方案,我很高兴听到它? :D – Lord

+0

@老爷对不起,但你不清楚你想做什么。你可能会添加更多的代码,并添加一些关于最终目标的细节?谢谢。 – alecxe

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) 
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