[英]Python selenium - Find element in elements loop
I would like to ask for help.我想寻求帮助。 I try on website https://www.kununu.com/de/volkswagen/kommentare/100 scrape overall rating under main title of all articles but when I do it, it will print:
我在网站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
But there are more ratings not just 4,8.但是还有更多的评分,而不仅仅是 4,8。 So I want to find element in elements loop.
所以我想在元素循环中找到元素。 I would like to do it in this type of loop if it's possible.
如果可能的话,我想在这种类型的循环中进行。 Here is my code:
这是我的代码:
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)
You've already gathered all the elements in art.你已经收集了艺术中的所有元素。
All you have to do is:您所要做的就是:
art = driver.find_elements_by_xpath("//article[@class='index__contentBlock__7vKo-']")
for i in art:
print(i.text)
Let me know if that works.让我知道这是否有效。
This should print all articles with index_score.这应该打印所有带有 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)
To extract the ratings eg 2,0 using Selenium and python you have to induce WebDriverWait for visibility_of_all_elements_located()
and you can use either of the following Locator Strategies :要使用Selenium和python提取评分(例如2,0) ,您必须为
visibility_of_all_elements_located()
引入WebDriverWait ,您可以使用以下任一定位器策略:
Using CSS_SELECTOR
and get_attribute("innerHTML")
:使用
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__']")))])
Using XPATH
and text attribute:使用
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__')]")))])
Console Output:控制台输出:
['2,0', '4,5', '3,8', '4,8', '2,8', '4,7', '3,2', '4,0', '4,9', '4,2']
Note : You have to add the following imports :注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
Link to useful documentation:链接到有用的文档:
get_attribute()
method Gets the given attribute or property of the element.
get_attribute()
方法Gets the given attribute or property of the element.
text
attribute returns The text of the element.
text
属性返回The text of the element.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.