python - How can I find an element looping through a list of divs using Selenium?
问题描述
In an HTML file structured like this:
<div class="card">
<div class="id">
ID: 123456
</div>
<div class="title">
Title 1
</div>
<div class="description">
Description 1
</div>
</div>
<div class="card">
<div class="id">
ID: 89123
</div>
<div class="title">
Title 2
</div>
</div>
Let's say that I have a variable number of divs with the class "card", using Selenium I would like to loop through these divs and if there is div with the class description, I would like to print his text.
I tried to do something like code below, but using find_element_by_xpath
. I will always get the first element that has the class "description". How can I fix this and properly-getting elements by looping through divs? Thanks a lot.
cards = webdriver.find_elements_by_xpath("//div[@class='main-div']")
for card in cards:
try:
description = card.find_element_by_xpath("//div[@class='description']")
print(description.text)
except:
print("No description")
解决方案
只.
用于intermediate
子标签。所以应该是这样的
card.find_element_by_xpath(".//div[@class='description']")
代码在这里:
cards = webdriver.find_elements_by_xpath("//div[@class='card']")
for card in cards:
try:
description = card.find_element_by_xpath(".//div[@class='description']")
print(description.text)
except:
print("No description")
推荐阅读
- node.js - Express, Mongoose, db.findOne always returns same document
- python - Django: python manage.py createdb Library not loaded: libmysqlclient.20.dylib
- python - 使用 findall 不返回匹配项的默认值填充数据框列
- java - 在 Java Web 服务中支持基于 IP 的白名单
- random - 不是真正随机的人工选择的伪随机变量?
- php - File could not be uploaded: missing temporary directory
- php - 在 Woocommerce 3 中以编程方式创建产品时设置产品类型
- c# - construct comma separated string from "name" property of objects stored in a list
- python - Dynamically resolve a pods address for get request
- html - 仅在 Edge 中使用 @font-face 定义的自定义字体