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

2024-04-26 20:45:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过单击相关链接导航到/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":{}}">

我尝试选择第一个使用:

^{pr2}$

它应该单击第一个项目,但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\\")]"}';

Tags: 链接counterjslinkbuttonthisclassyes
1条回答
网友
1楼 · 发布于 2024-04-26 20:45:45

您的XPath无效,这两个条件应放在同一方括号内(为便于阅读而设置格式):

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

未格式化版本:

^{pr2}$

相关问题 更多 >