我正在嘗試使用 selenium 自動下載報告。要進入報告所在的頁面,我必須點擊帶有此代碼的影像
<div class="leaflet-marker-icon single-icon-container running hover asset leaflet-zoom-hide leaflet-clickable" tabindex="0" style="margin-left: -22px; margin-top: -41px; width: 44px; height: 44px; opacity: 1; transform: translate3d(525px, 238px, 0px); z-index: 238;"><div class="icon-value" lid="219058"></div></div>
我試過
wtg = driver.find_elements_by_class_name(
"leaflet-marker-icon single-icon-container running hover asset leaflet-zoom-hide leaflet-clickable")
wtg.click()
但什么也沒有發生。有 7 個元素具有相同的類,并且看起來像一個唯一的“id”,lid="219058"但我不知道如何選擇它。
uj5u.com熱心網友回復:
leaflet-marker-icon single-icon-container running hover asset leaflet-zoom-hide leaflet-clickable包含多個類名而driver.find_element_by_class_name方法打算獲取單個類名。
我無法為您提供此元素的正確定位器,因為您沒有共享頁面鏈接,但是如果您希望根據這些類名組合定位該元素,您可以使用 CSS Selector 或 XPath,如下所示:
wtg = driver.find_element_by_css_selector(".leaflet-marker-icon.single-icon-container.running.hover.asset.leaflet-zoom-hide.leaflet-clickable")
wtg.click()
或者
wtg = driver.find_element_by_xpath("//*[@class='leaflet-marker-icon single-icon-container running hover asset leaflet-zoom-hide leaflet-clickable']")
wtg.click()
你也應該使用driver.find_element_by_class_name, notdriver.find_elements_by_class_name因為它driver.find_elements_by_class_name會給你一個 web 元素串列,而不是一個可以直接點擊的 web 元素。
或者,您可以使用 FLAK-ZOSO 所描述的接收到的 Web 元素串列中的第一個索引
uj5u.com熱心網友回復:
一般來說,構建網路爬蟲的最佳實踐是始終使用 xpath,因為 xpath 可以以更靈活的方式應用所有過濾器(id、class 等)(但在某些情況下,selenium 的性能可能會降低)。
我建議您查看這篇關于如何為各種需求撰寫 xpath 的文章:https ://www.softwaretestinghelp.com/xpath-writing-cheat-sheet-tutorial-examples/
對于您的特定用例,我會使用:
driver.find_element_by_xpath('//div[@lid="219058"]')
這實際上將單擊內部 div(注意蓋子實際上是如何位于嵌套 div 內的)。如果您想單擊外部 div,您可以使用:
driver.find_element_by_xpath('//div[@lid="219058"]/parent::div')
我再次建議您學習 Xpath 語法并始終使用它,它比其他 selenium 選擇器更易于操作,并且在您選擇實作 C 編譯的 html 決議器(例如 lxml)來決議元素的情況下也更快。
uj5u.com熱心網友回復:
請記住,driver.find_elements_by_class_name()回傳一個list.
使用此get/find方法時,您必須執行以下操作:
driver.find_elements_by_class_name('class')[0] #If you want the first of the page
在您的情況下,您需要使用 ,css_selector因為您有多個類,就像@Prophet 建議的那樣。您也可以只使用其中一個類,只需使用class_name選擇器即可。
在您的情況下,如果您需要具有該類的頁面的第一個元素,則必須添加[0].
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/384029.html
標籤:Python 硒 硒网络驱动程序 css-选择器 硒铬驱动器
