Selenium-python中CSS选择器的括号问题[?]
下面是我的脚本,用来检查某个元素是否存在。当我使用这个选择器:
css=input[name='flightSearchParam[3].originAirport']
在Selenium Ide中可以找到这个元素,但当我在selenium rc中运行时却找不到。我觉得这可能是括号的问题。
我需要做什么改变才能让selenium rc找到这个元素呢?
我是在Windows XP和波兰文化环境下运行的。
脚本已经准备好可以运行了。
# -*- coding: utf-8 -*-
from selenium import selenium
import unittest, time, re
class Untitled(unittest.TestCase):
def setUp(self):
self.verificationErrors = []
self.selenium = selenium("localhost", 5555, "*chrome", "http://www.aa.com/")
self.selenium.start()
def test_untitled(self):
sel = self.selenium
sel.open("/international/internationalSplashAccess.do?countryCodeForIP=PL")
sel.click("localeSubmit")
sel.wait_for_page_to_load("30000")
for i in range(60):
try:
if sel.is_element_present("aa-hp-multi-city-link2"): break
except: pass
time.sleep(1)
else: self.fail("time out")
sel.click("aa-hp-multi-city-link2")
sel.click("flightSearchForm.button.reSubmit")
sel.wait_for_page_to_load("30000")
for i in range(60):
try:
if sel.is_element_present(u"css=input[name='flightSearchParam[3].originAirport']"): break
except: pass
time.sleep(1)
else: self.fail("time out")
def tearDown(self):
self.selenium.stop()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
以下是主体部分:
conn.request("POST", "/selenium-server/driver/", body, headers)
u'cmd=isElementPresent&1=css%3Dinput%5Bname%3DflightSearchParam%5B2%5D.originAirport%5D&sessionId=02b3341a3fee46f5a1e6d9c13d6e8916'
编辑
我把它改成了 sel.is_element_present("dom=document.getElementsByName('flightSearchParam[3].originAirport')[0]"):
这样就能找到这个元素了。但是,我还是不明白为什么css在这里不工作 :/
4 个回答
0
试着用反斜杠来转义这些括号。
1
我遇到过类似的问题,可能能给你一些解决你问题的启发:
在使用Firefox的Selenium IDE录制时,它返回了这个目标:
css=input[name="keywords"]
要获取这个元素,正确的CSS选择器参数是(selenium 2.41版本):
solution = driver.find_element_by_css_selector('input[name="keywords"]')
所以,在你的情况下,这可能会有效:
css= 'input[name="flightSearchParam[3].originAirport"]'
solution = driver.find_element_by_css_selector(css)
注意:在Python的Selenium中,我从来不需要对表示索引的括号进行转义……
2
如果HTML代码是
<input name="flightSearchParam[3].originAirport">
那么它的CSS选择器将是
css=input[name='flightSearchParam\[3\].originAirport']
你需要对这个括号进行转义,因为它在CSS选择器中有特定的含义。