在Python selenium中,如何从具有相同名称的类中获取返回文本?

2024-10-01 22:36:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用selenium python捕获网页的产品大小

<h4 class="product-sizes">
 <!-- react-text: 510 -->Sizes: 
 <!-- /react-text -->
 <span class="product-sizeInventoryPresent">UK6,
 </span><span class="product-sizeInventoryPresent">UK7,
 </span><span class="product-sizeInventoryPresent">UK8,
 </span><span class="product-sizeInventoryPresent">UK9,
 </span><span class="product-sizeInventoryPresent">UK10,
 </span><span class="product-sizeInventoryPresent">UK11
</span>
</h4>

基本上,输出应该在类product-sizeInventoryPresent下列出所有大小,即大小=[UK6、UK7、UK8、UK9、UK10、UK11]。 到目前为止我试过这个

sizes = browser.find_elements_by_class_name('product-sizes')
size_list = []
for size in sizes:
    size_list.append(size.text)

但它返回一个空列表。主要是因为product-sizeInventoryPresent仅当我将鼠标悬停在元素上时才可见


Tags: textsizeproductreacth4classspansizes
1条回答
网友
1楼 · 发布于 2024-10-01 22:36:12

在selenium中,找到父元素后,可以使用父元素搜索子元素

请尝试以下代码:

parent = browser.find_elements_by_class_name('product-sizes')[0] # first in list
sizes = parent.find_elements_by_class_name('product-sizeInventoryPresent')  # children
size_list = []
for size in sizes:
    size_list.append(size.text)
    
print(size_list)

输出

['UK6,', 'UK7,', 'UK8,', 'UK9,', 'UK10,', 'UK11']

相关问题 更多 >

    热门问题