为了账号安全,请及时绑定邮箱和手机立即绑定

selenium.common.exceptions.InvalidSelector

selenium.common.exceptions.InvalidSelector

慕妹3146593 2021-10-19 10:18:09
我正在尝试编写一个脚本来处理具有多个元素的网页。单击此元素后将打开一个新窗口。但是我的脚本在识别元素方面存在问题。我需要帮助来定位元素并处理多个窗口我尝试使用 Chrome 查找 Xpath,但它在 Internet Explorer 中不一样。我也试过使用 CSS 选择器它不起作用。说是无效的。函数 test_google_search_page 的代码: def test_google_search_page(self): driver=self.driver driver.get(" http://xxxx.com ") str1=driver.title print(str1)    #get the window handles using window_handles    window_before=driver.window_handles[0]    print(window_before)    #driver.find_element_by_xpath("//*                   [@id='2ccb50dfc61122820032728dcea648fe']/div/div")    driver.find_element_by_css_selector("#\32  ccb50dfc61122820032728dcea648fe > div > div")    window_after=driver.window_handles[1]    driver.switch_to.window(window_after)    str2=driver.title    print(str2)    print(window_after)    self.assertNotEqual(str1,str2)    print('This window has a different title')    driver.switch_to.window(window_before)    self.assertEqual(str1,driver.title)    print('Returned to parent window. Title now match')ERROR: test_google_search_page (__main__.GoogleOrgSearch)----------------------------------------------------------------------Traceback (most recent call last):  File "C:\Users\PSWN672P\AppData\Local\Programs\Python\Python37\Python programs\SNOW2.py", line 21, in test_google_search_page    driver.find_element_by_css_selector("#\32 ccb50dfc61122820032728dcea648fe > div > div")  File "C:\Users\PSWN672P\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 598, in find_element_by_css_selector    return self.find_element(by=By.CSS_SELECTOR, value=css_selector)  File "C:\Users\PSWN672P\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element    'value': value})['value']
查看完整描述

2 回答

?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

您的#\32 ccb50dfc61122820032728dcea648fe > div > divCSS 选择器确实无效。请参考CSS 选择器语法规范

你的意思是:#2ccb50dfc61122820032728dcea648fe > div > div?尽管如此,如果不查看您试图定位的页面和元素的 HTML 源代码,就不可能为您提供特定的正确选择器。

2ccb50dfc61122820032728dcea648feID本身虽然看起来自动生成的,你应该寻找替代定位器来获得所需的元素

查看完整回答
反对 回复 2021-10-19
?
慕码人8056858

TA贡献1803条经验 获得超6个赞

这个错误信息...


driver.find_element_by_css_selector("#\32 ccb50dfc61122820032728dcea648fe > div > div")

.

selenium.common.exceptions.InvalidSelectorException: Message: An invalid or illegal selector was specified

...暗示CssSelector不是有效的。


在存在相关 HTML 的情况下构建最适合的CssSelector会更容易。但是,根据您的代码试验:


\32因为Id的值看起来不正确。

ccb50dfc61122820032728dcea648fe是动态生成的内容。所以也不能用。

在这里你可以找到CSS 选择器参考


查看完整回答
反对 回复 2021-10-19
  • 2 回答
  • 0 关注
  • 456 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号