2015-02-10 40 views
0

爲Python硒選擇元素我有這樣的HTML片段:InvalidSelectorException當使用XPath

<div class="btn"> 
    <a href="javascript:void(0)" class="S_btn_b" node-type="OK"> 
     <span>確定</span> 
    </a> 
</div> 

我要選擇確定元素並單擊它。我試着用xpath以下選擇:

confirm_btn = driver.find_element_by_xpath('//div[@class="btn"]//span[text()="確定"]') 

但該方案只是抱怨,是不是與此異常有效的選擇:

Traceback (most recent call last): 
    File "test.py", line 63, in <module> 
    ac.move_to_element(driver.find_element_by_xpath('//div[@class="btn"]/span[text()="確定"')) 
    File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 230, in find_element_by_xpath 
    return self.find_element(by=By.XPATH, value=xpath) 
    File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 662, in find_element 
    {'using': by, 'value': value})['value'] 
    File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 173, in execute 
    self.error_handler.check_response(response) 
    File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 166, in check_response 
    raise exception_class(message, screen, stacktrace) 
selenium.common.exceptions.InvalidSelectorException 

難道我做錯了什麼?

+0

如果只用''// div [@ class =「btn」] // span''嘗試會發生什麼? – 2015-02-10 11:02:33

+0

@MathiasMüller似乎沒有指定'span'的'text()'可能是引號出現問題嗎? – armnotstrong 2015-02-10 11:10:14

+0

不,但似乎不支持這些字符(中文?)。 – 2015-02-10 11:12:12

回答

3

如果您沒有將XPath表達式標記爲Unicode,則當搜索命令發送到瀏覽器時,漢字將會變形並且搜索將搜索除您想要的外的其他內容,因此請將您的XPath表達式標記爲Unicode:

confirm_btn = driver.find_element_by_xpath(u'//div[@class="btn"]//span[text()="確定"]')