簡體   English   中英

按xpath查找元素並單擊它

[英]Find element by xpath and click on it

我正在嘗試在頁面上加載完整的圖像列表。 頁面上有一個“顯示更多”按鈕。 我想點擊它直到加載所有圖像。

HTML:

<li class="show-more-row">
    <button class="show-more-cta bottom-btn ga"data-ga-action="click"data-ga-label="category-see-more:SectionCourses>Show More
        <i class="lyndacon arrow-down"></i>
    </button>
</li>

我必須嘗試通過Xpath獲取元素。 但每次點擊按鈕時它都會不斷變化。

例:

//*[@id="category-courses"]/li[101]/button and //*[@id="category-courses"]/li[151]/button

我也嘗試按類名查找元素:

while(browser.find_element_by_class_name("show-more-cta bottom-btn ga")):
    moreElem = browser.find_element_by_class_name("show-more-cta bottom-btn ga")
    moreElem.click()

但它給出了錯誤:

無效的選擇器:不允許使用復合類名

復合/多個類不能在“按類名”定位器中使用 您必須在定位器中保留一個類:

browser.find_element_by_class_name("show-more-cta")

或者,使用不同的策略,例如CSS選擇器:

browser.find_element_by_css_selector(".show-more-cta.bottom-btn.ga")

請注意,我只留下一個“show-more-cta”類 - 它是一個很好的選擇,因為它為定位器帶來了價值和意義,使其可讀。 另一方面, bottom-btnga類在這種情況下沒有任何實質意義 - 這些類是面向布局/設計/標記的。

嘗試使用相對XPath而不是絕對XPathclass_name

browser.find_element_by_xpath("//button[@class='show-more-cta bottom-btn ga']")

要么

browser.find_element_by_xpath("//button[.='Show More']")

暫無
暫無

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

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