首页 > 解决方案 > 美丽汤找不到元素时如何处理属性错误

问题描述

我正在尝试抓取黎巴嫩的一个房地产网站,有些房产有其可用设施的描述,有些则没有。

在将要抓取的链接存储在 excel 列中之后,我遍历它们以访问它们并提取该属性的可用设施。

但是有些属性是土地,例如,那些没有任何便利设施,所以当我的代码遇到这种情况时,它会引发“属性错误”。

下面的代码是使用 try and except 方案,但我想要的是在我存储我的设施soupObject 的列表中设置一个“没有设施”值,当没有设施时。

任何帮助将非常感激,

import bs4
import requests


amenity_soupObject=[]
for cellObj in sheet['A']: ##here the A represents the column name
    try:
        link = cellObj.value
        ress = requests.get(link)
        time.sleep(0.2)
        soup_finder = bs4.BeautifulSoup(ress.text) 


        propAmenities=soup_finder.find("div", class_="amenities_container")
        propAmenities1 = bs4.BeautifulSoup(propAmenities.text)
        amenity_soupObject.append(propAmenities1)
        print(propAmenities1)

     except: "AttributeError"
         amenity_soupObject.append("no amenities here")

标签: pythonwebweb-scrapingbeautifulsoup

解决方案


推荐阅读