Selenium CSS 选择器仅获取第一个元素,而检查器显示 4

Selenium CSS Selector get only first element while the inspector show 4

我正在尝试使用 Selenium 自动化 Linguee 词典。

例如,在图像中我想得到一个数组 [de, para, por, con]。为了得到这个,我写了下面的代码

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.by import By

s=Service(r"C:\Users\Usuario\python\geckodriver.exe")
driver = webdriver.Firefox(service=s)

driver.get('https://www.linguee.fr/frances-espanol/')
consent_button=driver.find_element(By.CSS_SELECTOR, "div[class='sn-b-def sn-blue']")
consent_button.click()


search_input=driver.find_element(By.CSS_SELECTOR, "input[id='queryinput']")
search_input.send_keys("de")

buttonSearch=driver.find_element(By.CSS_SELECTOR, "button[alt='Rechercher dans le dictionnaire français-espagnol']")
buttonSearch.click()

wortType=driver.find_element(By.CSS_SELECTOR, "span[class='tag_wordtype']").text
print( wortType)

translations=driver.find_element(By.CSS_SELECTOR, "div[class='isMainTerm'] a[class='dictLink']").text
print(translations)

代码工作正常,但它 returns 只有第一个翻译(图像中的“en”),而在浏览器控制台中我得到 4。所以,我一直在阅读并尝试不同的修复方法问题,比如更改 CSS_SELECTOR

translations=driver.find_element(By.CSS_SELECTOR,"div[class='isMainTerm'] div[class='exact'] div[class='lemma featured'] div[class='lemma_content'] div[gid=0] div[class='translation_lines'] div[class='translation sortablemg featured'] a")
translations=driver.find_element(By.CSS_SELECTOR, "div[class='isMainTerm'] a[class='dictLink']").text
translations=driver.find_element(By.CSS_SELECTOR, "div[class='isMainTerm'] a[class='dictLink']")
translations=driver.find_element(By.CSS_SELECTOR,"div.isMainTerm div.lemma_content a.dictLink").text
translations=driver.find_element(By.CSS_SELECTOR, "div[class='isMainTerm']> a[class='dictLink featured']").text

我也用过 XPath,但 returns 只用过一个。 我在 Whosebug 中阅读了不同的 post 类似的问题 ,但问题仍然存在。

抱歉,这是冗长的,但是有人可以指导我为什么这样做以及我的选择是什么吗?

这就是 find_element 方法的工作原理。
它 returns 它找到的 DOM 上的 第一个 匹配元素。
因此,如果您向它传递匹配页面上多个元素的定位器,将返回 DOM 上的第一个匹配元素。
如果您想获得 all 匹配该定位器的元素 find_elements 方法应该被使用。
因此,如果您想获取匹配 div[class='isMainTerm'] a[class='dictLink'] CSS 选择器而不是

的元素中的所有文本
translations=driver.find_element(By.CSS_SELECTOR, "div[class='isMainTerm'] a[class='dictLink']").text
print(translations)

你可以使用

translations = driver.find_elements(By.CSS_SELECTOR, "div[class='isMainTerm'] a[class='dictLink']")
for translation in translations:
    print(translation.text)

顺便说一句,只有这个 CSS 选择器定位器 div[class='isMainTerm'] a[class='dictLink featured'] 匹配你提到的 4 个元素,看起来你应该在这里使用这个定位器,而 div[class='isMainTerm'] a[class='dictLink'] 定位器匹配 81元素!在那个页面上。