Python 使用Selenium循环通过CSS选择器时,选择器无效或非法
我试图使用Selenium在一个表中循环一系列行,但发现在尝试这样做时出现了一个错误。代码应该循环并捕获变量中的每一行,然后将其与引用变量进行比较,但它会抛出一个错误,表明我添加了无效或非法的选择器 请在下面找到我的代码:Python 使用Selenium循环通过CSS选择器时,选择器无效或非法,python,selenium,selenium-webdriver,css-selectors,Python,Selenium,Selenium Webdriver,Css Selectors,我试图使用Selenium在一个表中循环一系列行,但发现在尝试这样做时出现了一个错误。代码应该循环并捕获变量中的每一行,然后将其与引用变量进行比较,但它会抛出一个错误,表明我添加了无效或非法的选择器 请在下面找到我的代码: for record in range(35, 2, -1): current_record = self.browser.find_element_by_css_selector('#web-body > div > div _
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
问题在于您试图将
记录
循环变量添加到选择器中。您已经使用了以下选项(为了简洁起见,省略了完整、复杂的选择器):
你真正想要的是这样的东西:
# Warning: below code might not
# be syntactically correct Python
'tr:nth-child(' + record + ')'
鉴于这是Python,您应该能够使用字符串格式将术语正确替换到选择器字符串中。有关如何执行此操作的完整详细信息,请参阅Python文档。问题在于您试图将
记录
循环变量添加到选择器中。您已经使用了以下选项(为了简洁起见,省略了完整、复杂的选择器):
你真正想要的是这样的东西:
# Warning: below code might not
# be syntactically correct Python
'tr:nth-child(' + record + ')'
鉴于这是Python,您应该能够使用字符串格式将术语正确替换到选择器字符串中。有关如何做到这一点的详细信息,请参阅Python文档。@JimEvans的分析方向正确 该函数返回一个数字序列,默认情况下从0开始,递增1(默认情况下),并以指定的数字结束 所以这个表达:
for record in range(35, 2, -1)
将返回35、34、33等数字序列,直到2
因此,当使用变量record
保存序列中的数字时,要在find\u element\u中通过
方法传递它,需要将其转换为string
因此,您需要更换零件:
tr:nth-child(record)
作为:
@JimEvans的分析方向是正确的 该函数返回一个数字序列,默认情况下从0开始,递增1(默认情况下),并以指定的数字结束 所以这个表达:
for record in range(35, 2, -1)
将返回35、34、33等数字序列,直到2
因此,当使用变量record
保存序列中的数字时,要在find\u element\u中通过
方法传递它,需要将其转换为string
因此,您需要更换零件:
tr:nth-child(record)
作为:
下划线是什么意思?下划线是什么意思?