我正在尝试从多个 div 中删除第一个子项 (span) 的类名。
这是html代码:
<div class="ui_column is-9">
<span class="name1></span>
<span class="...">...</span>
...
<div class ="ui_column is-9">
<span class="name2></span>
<span class="...">...</span>
...
<div class ..
URL页面的完整代码。
我正在使用前五个 div 的代码完成此任务:
i=0
liste=[]
while i <= 4:
parent= driver.find_elements_by_xpath("//div[@class='ui_column is-9']")[i]
child= parent.find_element_by_xpath("./child::*")
class_name= child.get_attribute('class')
i = i+1
liste.append(nom_classe)
但是您知道是否有更简单的方法吗?
最佳答案
可以直接获取所有这些first span
元素,然后提取它们的class
属性值如下:
liste = []
first_spans = driver.find_elements_by_xpath("//div[@class='ui_column is-9']//span[1]")
for element in first_spans:
class_name= element.get_attribute('class')
liste.append(class_name)
您还可以通过将循环限制为 5 次迭代,仅从前 5 个元素中提取 class
属性值
UPD
好吧,在更新您的问题后,答案变得不同且简单得多。
您可以直接获取所需的元素,并提取其类名属性值,如下所示:
liste = []
first_spans = driver.find_elements_by_xpath("//div[@class='ui_column is-9']//span[contains(@class,'ui_bubble_rating')]")
for element in first_spans:
class_name= element.get_attribute('class')
liste.append(class_name)
关于python - 从多个 div (selenium) 中抓取第一个 child 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70485643/