【问题标题】:count numbers of tag_name in a webpage (python, selenium)计算网页中 tag_name 的数量(python、selenium)
【发布时间】:2016-06-29 19:30:19
【问题描述】:

你好有以下代码:

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]

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

是否可以检查for each 内的tds 的数量以使find_elements_by_tag_name('td') 动态化?

【问题讨论】:

    标签: python html selenium xpath webpage


    【解决方案1】:

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

    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]
    

    【讨论】:

    • 感谢您的回答!!! :) 我的问题是我需要索引才能在我的 sql 数据库中正确插入数据,否则我不知道如何插入它们......对不起,但我是 python 和 sql 的新手......但如果你有更好的解决方案我很高兴听到它? :D
    • @Lord 抱歉,但不清楚您要做什么。您是否可以添加到目前为止的更多代码并添加一些有关您的最终目标的详细信息?谢谢。
    【解决方案2】:

    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)
    

    【讨论】:

      【解决方案3】:

      从阅读您的 cmets 来看,这似乎是您正在尝试做的事情......

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-03
        • 2011-09-05
        • 1970-01-01
        • 2022-12-07
        • 1970-01-01
        • 1970-01-01
        • 2013-08-20
        • 1970-01-01
        相关资源
        最近更新 更多