Selenium在Python中选择带有xpath的元素

时间:2014-07-12 17:24:10

标签: python selenium xpath

我想通过点击相关链接导航到/yandsearch?...。页面中有两个链接:

<a class="button button_theme_pseudo button_pseudo-pressed_yes button_size_m button_counter_yes button_focus_no b-link b-link_pseudo_yes pager__button pager__button_kind_page i-bem button_js_inited" onmousedown="w(this, '405.88');" href="/yandsearch?lr=157&text=landsad&p=3" role="button" ondblclick="return {"button":{"counter":"w(this, '405.88');"},"b-link":{}}">
<a class="button button_theme_pseudo button_pseudo-pressed_yes button_size_m button_counter_yes button_focus_no b-link b-link_pseudo_yes pager__button pager__button_kind_page i-bem" onmousedown="w(this, '405.88');" href="/yandsearch?lr=157&text=landsad&p=3" role="button" ondblclick="return {"button":{"counter":"w(this, '405.88');"},"b-link":{}}">

我尝试选择第一个使用:

driver.find_element_by_xpath(str('//*[contains(@href,"yandsearch?lr=157&text=landsad&p=3")] and [contains(@class,"button_js_inited")]')

它应该点击第一个项目,但find_element_by_xpath无法找到它 我收到错误:

    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: 'The given selecto......

我想点击第4页的yandex.by/yandsearch

链接

我也试过了:

//*[contains(@href,"yandsearch?lr=157&text=landsad&p=3") and contains(@class,"button_js_inited")]

写错误:

self.error_handler.check_response(response) File "C:\Python34\lib\site- packages\selenium\webdriver\remote\errorhandler.py" , 
line 164, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: 
Message: 'Unable to locate element: {"method":"xpath","selector":"//* [contains(@href,\\"yandsearch?lr=157&tex t=landsad&p=3\\") and contains(@class,\\"button_js_inited\\")]"}';

1 个答案:

答案 0 :(得分:0)

您的XPath无效,两个条件都应放在相同的方括号内(格式为readiblity):

//*[
        contains(@href,"yandsearch?lr=157&text=landsad&p=3") 
            and 
        contains(@class,"button_js_inited")
   ]

未格式化版本:

//*[contains(@href,"yandsearch?lr=157&text=landsad&p=3") and contains(@class,"button_js_inited")]