代码之家  ›  专栏  ›  技术社区  ›  LucSpan

在含硒的tbody中迭代tr

  •  2
  • LucSpan  · 技术社区  · 6 年前

    组织

    我在WordPress后端有一个包含几行的表。每一行都包含一个我想使用Selenium打开的链接。

    也就是说,我想在每个 <tr> 在里面 <tbody> .

    browser 定义为:,

    browser = webdriver.Firefox(executable_path='mypath')

    这个 <t车身> 具有通常的形式,

     <tbody>
        <tr>...</tr>
        ...
        <tr>...</tr>
     </tbody>
    

    迄今为止的代码

    • 仅有一个的 <tr>

    导航到正确的页面后,

    tbody = browser.find_element_by_css_selector('.widefat > tbody:nth-child(2)')
    
    browser.find_element_by_xpath('//*[@title="Dutch: Add translation"]').click()
    

    这个 <t车身> 元素已正确选择,并且第一个元素的右链接 <tr> 已正确打开。

    • 循环结束 <tr>

    我不知道如何在所有 <tr> 在中 <t车身> .

    我尝试了以下方法,

    tbody = browser.find_element_by_css_selector('.widefat > tbody:nth-child(2)')
    
    for row in tbody.find_element_by_xpath('./tr'):
        browser.find_element_by_xpath('//*[@title="Dutch: Add translation"]').click()
    

    但这给了 TypeError: 'FirefoxWebElement' object is not iterable .

    清晰地 tbody.find_element_by_xpath('./tr') 不是选择全部的正确方法 <tr> 是的。

    如何全选 <tr> 是否正确?

    3 回复  |  直到 6 年前
        1
  •  8
  •   Andersson    6 年前

    for row in tbody.find_element_by_xpath('./tr') 打算迭代 仅有一个的 WebElement,而您需要遍历 列表 元素的数量:

    for row in tbody.find_elements_by_xpath('./tr')
    
        2
  •  4
  •   Omar Einea Man    6 年前

    使用(注意 s ):

    tbody.find_elements_by_xpath('./tr')
    

    而不是:

    tbody.find_element_by_xpath('./tr')
    

    只返回第一个匹配项。

        3
  •  0
  •   Wojciech Jakubas    6 年前

    您可以使用 find_element_by_xpath 方法,但也 find_elements_by_tag_name 我更喜欢用它。

    tbody_rows = tbody.find_elements_by_tag_name('tr')
    for tbody_row in tbody_rows:
        #do your stuff here with each row in turn