如何使用selenium和python动态读取表中的特定单元格值

2024-10-01 09:16:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个自动化脚本[使用selenium和python],它应该完成以下工作

  1. 动态读取表格的行和列,查找在任何行中设置了0值的列[this is constant],如果找到,请单击同一行中的[assign/unassign]按钮列

我不想硬编码值为“0”的列的xpath,而是动态地查找它并继续。在

下面的代码是我写的

trows = table1.find_elements_by_xpath("//table[@id='ambassadors-for-assignment']/tbody/tr")
row_count = len(trows)
tcols = trows.find_elements_by_xpath("//table[@id='ambassadors-for-assignment']/tbody/tr/td")
col_count = len(tcols)
first_part = "//table[@id=ambassadors-for-assignment']/tbody/tr["
second_part = "]/td["
third_part = "]"
for i in range(1, len(row_count)):
    for j in range(1, len(col_count)):
          final_xpath = first_part+i+second_part+j+third_part      

HTML文件结构

^{pr2}$

我的HTML文件有n行,列数如上所示。如前所述,我想读取第三列的值[即10 | 5],看看它是否为0[只考虑第三列中的第一项],然后单击下一列中的[btn btn success]按钮。在

如有任何进一步的建议,我们将不胜感激!在

我将在评论部分提供到实际HTML文件的链接


Tags: 文件idforlenhtmlcounttable动态
1条回答
网友
1楼 · 发布于 2024-10-01 09:16:49

I do not want to hard-code the xpath of the column that has value "0"

from selenium import webdriver
import re

driver = webdriver.PhantomJS()
driver.set_window_size(1120, 550) #For bug
driver.get("http://localhost:8000")

pattern = r"""
    \s*         #Match whitespace, 0 or more times, followed by...
    (\d+)       #a digit, one or more times, captured, followed by
    \s*         #whitespace, 0 or more times, followed by...
    [|]         #vertical bar, followed by...
    \s*         #whitespace, 0 or more times, followed by...
    \d+         #a digit, one or more times
"""
regex = re.compile(pattern, re.X)

table = driver.find_element_by_id('ambassadors-for-assignment')
trs = table.find_elements_by_tag_name('tr')

for tr in trs:
    tds = tr.find_elements_by_tag_name('td')

    for td in tds:
        match_obj = re.search(regex, text)

        if match_obj and match_obj.group(1) == '0':
            success_button = tr.find_element_by_css_selector('button.btn-success')
            print success_button.get_attribute('type')
            success_button.click()

在重新匹配(模式、字符串、标志=0)
如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的匹配对象。如果字符串与模式不匹配,则返回None;请注意,这与零长度匹配不同。在

请注意,即使在多行模式下,重新匹配()将只在字符串的开头匹配,而不是在每行的开头匹配。在

如果要在字符串中的任何位置找到匹配项,请改用search()(另请参见search()与match())。在

https://docs.python.org/3/library/re.html#module-re

======

这里是xpath,我认为它更符合您正在尝试的操作,即给定一个列,在行中查找值0:

^{pr2}$

根据要与正则表达式匹配的文本,输出将如下所示:

column 3:
0 | 5
btn btn-success

column 4:
0 | 61
btn btn-success

但在我看来,必须在xpath中使用以下内容:

'[contains(concat(" ", normalize-space(@class), " "), " btn-success ")]'

要匹配一个类,这意味着使用xpath不是一种方法。python方法:

find_element_by_csss_selector('button.btn-success')

…会更简洁明了地做同样的事情。在

相关问题 更多 >