【问题标题】:Invalid or illegal selector while looping through CSS Selector with Selenium使用 Selenium 循环通过 CSS 选择器时选择器无效或非法
【发布时间】:2018-11-13 17:53:39
【问题描述】:

我正在尝试使用 Selenium 遍历表中的一堆行,但我发现在尝试这样做时出现错误。代码应该循环并捕获变量中的每一行,然后将其与我的引用变量进行比较,但它会抛出一个错误,表明我添加了一个无效或非法的选择器。

请在下面找到我的代码:

for record in range(35, 2, -1):

        current_record = self.browser.find_element_by_css_selector('#web-body > div > div _
        > div > div > div > div > _
        div:nth-child(2) > div > div > div > div > div > div:nth-child(2) _
        > div.FieldLayout---input_below > div > _
        div.PagingGridLayout---scrollable_content > table _
        > tbody > tr:nth-child(record) > td:nth-child(2) > div > p > a')

        print('the current record is: ' + current_record.text) 
        #print the current record for debugging purposes

        if self.entry_test_id != current_record.text: 
            continue 
            #if the current record in the loop != the correct record, go to the next record

        else:
            web_was_record_found = True #note that record was found for next check

            actions.key_down(Keys.SHIFT).click(current_record).key_up(Keys.SHIFT).perform() 
            #open the found record in a new WINDOW

【问题讨论】:

  • 下划线_是什么意思?

标签: python selenium selenium-webdriver css-selectors


【解决方案1】:

问题在于您尝试将 record 循环变量添加到选择器中。您使用了以下内容(为简洁起见,省略了完整的、复杂的选择器):

'tr:nth-child(record)'

你真正想要的是这样的:

# Warning: below code might not
# be syntactically correct Python
'tr:nth-child(' + record + ')'

鉴于这是 Python,您应该能够使用字符串格式将术语正确替换到选择器字符串中。有关如何执行此操作的完整详细信息,请参阅 Python 的文档。

【讨论】:

    【解决方案2】:

    @JimEvans 的分析方向正确。

    range() 函数返回一个数字序列,默认从 0 开始,并以 1(默认)递增,并以指定的数字结束。

    所以表达式:

    for record in range(35, 2, -1)
    

    将返回数字序列为 35、34、33 等直到 2。

    因此,当使用变量record 保存序列中的数字时,要在find_element_by_css_selector() 方法中传递它,您需要将其转换为string

    所以你需要更换零件:

    tr:nth-child(record)
    

    作为:

    tr:nth-child(str(record))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 2020-11-11
      • 2023-03-28
      • 2020-06-25
      • 1970-01-01
      • 2020-05-22
      相关资源
      最近更新 更多