如何解析包含不同对象类型的HTML表?

时间:2018-10-17 10:00:48

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

我有一个HTML表,该表包含以下对象类型:文本,文本框,列表框(选择)和按钮(请参见所附图片)。
我的目的是在可能的情况下分析表中的文本。

例如,我想解析“用户名”,“权限”,“ SNMPv3身份验证”和“ SNMPv3 Priv”列。 The Table to Parse

对于列表框,我已经知道如何收集所选的选项文本。
仅包含文本的表对我来说是众所周知的,我知道如何很好地解析它们,但是我用来解析它们的方法并不适合这种表。

您如何建议我处理这种桌子?

在代码示例中,我打印了表格的内容(文本),但实际上,我将其存储以分析表格的内容。顺便说一句,您还可以看到我没有在引用表的第一行(标题)。

这是用户如何查看仅具有div标签的列表行的方式 enter image description here

2 个答案:

答案 0 :(得分:2)

根据您共享的html,每个tr都有三个元素,文本框,选择框和按钮。

在保存的记录的屏幕快照中,我也没有看到输入字段。例如,文本user1。我假设user1在span标签内。 喜欢

<td>
 <div>user1</div>
</td> 

您必须以不同方式处理每个元素,以从中获取价值。

  • 要在div中获取innerText,我们必须使用elem.text
  • 获取属性 输入文本框的值,我们必须使用elem.get_attribute('value')
  • 要获取所选值,我们必须使用Select(elem).first_selected_option

这是示例代码,用于获取您的dom的数据。请根据需要自由编辑。 我已经使用CSS选择器来查找元素。在here中查找语法。

# This returns all the tr elements in the table
rows = driver.find_elements_by_css_selector("table#sec_user_table>tbody>tr")
for i in range(1, len(rows)):
    # This returns only the span, input which is not password and select elements
    cols = rows[i].find_elements_by_xpath("td//*[self::div[not(.//input)] or self::input[@type='text'] or self::select]")
    for col in cols:
        if col.tag_name == 'SELECT':
            print(Select(col).first_selected_option.text) # To get the select value
        elif col.tag_name == 'INPUT':
            print(col.get_attribute('value'))    # To get the input value
        else:
            print(col.text)    # To get text fron span

具有单个选择器的简单解决方案:

这是特定于您的情况的,因为您不需要完全输入元素

  # This returns all the tr elements in the table
    rows = driver.find_elements_by_css_selector("table#sec_user_table>tbody>tr")
    for i in range(1, len(rows)):
        username = rows[i].find_element_by_xpath("//div[not(.//input)]")
        print(username.text)

        select = rows[i].find_elements_by_css_selector("select")
        for col in cols:
            print(Select(col).first_selected_option.text) # To get the select value

答案 1 :(得分:0)

我改进了上述解决方案来解决我的特定问题,它仍然可能需要进行一些调整,例如,我需要考虑一种忽略最后一行的方法,但这并不是一个大问题。我要解决的另一件事是获得结果所需的时间。由于某种原因,它需要几秒钟

rows = driver.find_elements_by_css_selector("table#sec_user_table>tbody>tr")
for row in rows:
   cols = row.find_elements_by_css_selector("div,select")
   for col in cols:
       if col.tag_name == 'div':
           if col.text != '':
               print(col.text)
       elif col.tag_name == 'select':
           print(Select(col).first_selected_option.text)