当beautifull soup找不到元素时如何处理属性错误

2024-04-26 05:27:59 发布

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

我正试图搜刮黎巴嫩的一个房地产网站,有些酒店有关于其可用设施的描述,有些则没有

在将要刮取的链接存储在excel列中之后,我对它们进行迭代以访问它们并提取该属性的可用便利设施

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

下面的代码是try-and-except方案,但我想要的是在列表中设置一个“no-commercies”值,当没有任何commercies soupObject时,我将在列表中存储我的commercies soupObject

任何帮助都将不胜感激

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")

Tags: theno代码列表属性herelinktry