[英]Python selenium - Find element in elements loop
我想尋求幫助。 我在網站https://www.kununu.com/de/volkswagen/kommentare/100上嘗試在所有文章的主標題下抓取總體評分,但是當我這樣做時,它會打印:
4,8
4,8
4,8
4,8
4,8
4,8
4,8
4,8
4,8
4,8
4,8
但是還有更多的評分,而不僅僅是 4,8。 所以我想在元素循環中找到元素。 如果可能的話,我想在這種類型的循環中進行。 這是我的代碼:
art = driver.find_elements_by_xpath("//article[@class='index__contentBlock__7vKo-']")
for i in art:
pr = i.find_element_by_xpath("//span[@class='index__score__16yy9']").text
print(pr)
你已經收集了藝術中的所有元素。
您所要做的就是:
art = driver.find_elements_by_xpath("//article[@class='index__contentBlock__7vKo-']")
for i in art:
print(i.text)
讓我知道這是否有效。
這應該打印所有帶有 index_score 的文章。
art = driver.find_elements_by_xpath("//article[@class='index__contentBlock__7vKo-']//span[@class='index__score__16yy9']")
for i in art:
print(i.text)
要使用Selenium和python提取評分(例如2,0) ,您必須為visibility_of_all_elements_located()
引入WebDriverWait ,您可以使用以下任一定位器策略:
使用CSS_SELECTOR
和get_attribute("innerHTML")
:
driver.get('https://www.kununu.com/de/volkswagen/kommentare/100') print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div[class^='index__ratingBlock'] span[class^='index__score__']")))])
使用XPATH
和text屬性:
driver.get('https://www.kununu.com/de/volkswagen/kommentare/100') print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[starts-with(@class, 'index__ratingBlock')]//span[starts-with(@class, 'index__score__')]")))])
控制台輸出:
['2,0', '4,5', '3,8', '4,8', '2,8', '4,7', '3,2', '4,0', '4,9', '4,2']
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
鏈接到有用的文檔:
get_attribute()
方法Gets the given attribute or property of the element.
text
屬性返回The text of the element.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.