Python Scrapy无法从每个div中获取每个类名及其值

jdzmm42g  于 2022-11-09  发布在  Python
关注(0)|答案(1)|浏览(133)

我试图从每个div列表中获取每个类名及其对应的值。
从此页面:https://www.dotproperty.id/en/properties-for-sale/riau-islands/batam?page=1

以下是类名称和值的html:

<ul class="list-inline">
<li><i class="icon icon-bedroom"></i> <span>3</span></li>
<li><i class="icon icon-dp-icon-24"></i> <span>2</span></li>
<li><i class="icon icon-dp-icon-26"></i> <span>100 m<sup>2</sup></span></li>
</ul>

到目前为止,我得到的最接近的结果是,它使用getall()并排打印每个类及其值。但是,它给了我整个页面。

for e in response.css('div.description-block'):
     for item in e.xpath('.//ul[@class="list-inline"]'):
         print(item.xpath('.//li/i/@class | .//li/span/text()').getall())

输出:

['icon icon-bedroom', '3', 'icon icon-dp-icon-24', '2', 'icon icon-dp-icon-26', '100 m']
['icon icon-bedroom', '2', 'icon icon-dp-icon-24', '1']
['icon icon-bedroom', '6', 'icon icon-dp-icon-24', '5', 'icon icon-dp-icon-26', '198 m']
['icon icon-bedroom', '4', 'icon icon-dp-icon-24', '5', 'icon icon-dp-icon-26', '450 m']
['icon icon-dp-icon-26', '336 m', ' ']

尝试get()给出每个div的每个第一个类名:

icon icon-bedroom
icon icon-bedroom
icon icon-bedroom
icon icon-bedroom
icon icon-dp-icon-26
(and so on ...)

我希望每个循环的输出都像这样。

['icon icon-bedroom', '3', 'icon icon-dp-icon-24', '2', 'icon icon-dp-icon-26', '100 m']
pgccezyw

pgccezyw1#

好的,我解决了我的问题。基本上,我只需要在图标容器内迭代,并通过名称区分每个图标。
在循环中循环。:)

for a in accommodation:
        class_name = a.xpath('.//i/@class').getall()
        value = a.xpath('li/span/text()').getall()
        for name,val in zip(class_name,value):
            if 'bedroom' in name:
                bedrooms = val
            else:
                pass
            if 'icon-24' in name:
                bathrooms = val
            else:
                pass
            if 'icon-26' in name:
                land = val
            else:
                pass

相关问题