在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
你的XPath写得不对,两个条件应该放在同一对方括号里(为了更好阅读,下面是格式化后的版本):
//*[
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")]