簡體   English   中英

Selenium在Python中使用xpath選擇一個元素

[英]Selenium select an element with xpath in 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":{}}">

我嘗試選擇第一個使用:

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......

我想單擊此鏈接yandex.by/yandsearch第4頁

我也嘗試過:

//*[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\\")]"}';

您的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")]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM