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

时间:2015-01-07 20:22:41

标签: python python-2.7 selenium selenium-webdriver

我正在开发一个自动化脚本[使用selenium和python],它应该执行以下操作

  1. 动态读取表行和列,查找列[这是常量],其中任何一行中都设置了0值,如果找到则单击同一行中的[assign / unassign]按钮列
  2. 我不想对值为“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文件结构

    <tbody>
      <tr>
        <td> james </td>
        <td> watson </td>
        <td> 10 | 5 </td>
        <td>
          <div class="btn-group" role="group">
             <button class="btn btn-success" type="button">
                 <i class="fa fa-plus"></i>
             </button>
            <button class="btn btn-danger" type="button">
                <i class="fa fa-minus"></i>
            </button>
          </div>
        </td>
      </tr>
    ....
    

    我的HTML文件有n行,上面给出了列。正如我所提到的,我想阅读第三列值[即10 | 5]看看它的0是否[仅考虑第三列中的第一项],然后在下一栏中点击[btn btn-success]按钮。

    任何进一步行动的指示都将不胜感激!

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

1 个答案:

答案 0 :(得分:0)

  

我不想硬编码具有值&#34; 0&#34;的列的xpath。

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

re.match(pattern,string,flags = 0)
如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的匹配对象。如果字符串与模式不匹配,则返回None;请注意,这与零长度匹配不同。

请注意,即使在MULTILINE模式下,re.match()也只会匹配字符串的开头而不是每行的开头。

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

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

<强> ==

这里是xpath,我认为它更符合你要做的事情,即给定一个列,向下看行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)

trs = driver.find_elements_by_xpath('//table[@id="ambassadors-for-assignment"]/tbody/tr')
target_columns = [3, 4]

for target_column in target_columns:
    for tr in trs:
        target_column_xpath = './td[{}]'.format(target_column)  #VARY COLUMN HERE ***
        td = tr.find_element_by_xpath(target_column_xpath)
        match_obj = re.match(regex, td.text)

        if match_obj and match_obj.group(1) == '0':
            button_xpath = './/button[contains(concat(" ", normalize-space(@class), " "), " btn-success ")]' 
            success_button = tr.find_element_by_xpath(button_xpath)
            #success_button.click()

            print "column {}:".format(target_column)
            print match_obj.group(0)
            print success_button.get_attribute('class')
            print

输出将如下所示,具体取决于您尝试与正则表达式匹配的文本:

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

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