Python爬取房产网站代理公司名遇NoneType属性错误求助
解决爬取point2homes房产列表时的AttributeError问题
问题出在你直接对find()返回的结果调用.text——当页面中某个房源没有代理名称(agent-name)或代理公司(agent-company)元素时,find()会返回None,此时调用.text就会触发AttributeError: 'NoneType' object has no attribute 'text'。
你已经对beds、baths、size做了异常处理,但address、type、price、agent、firm这些字段同样可能出现找不到元素的情况,需要统一处理。
修改后的代码
from bs4 import BeautifulSoup import requests url = "https://www.point2homes.com/MX/Real-Estate-Listings.html?LocationGeoId=&LocationGeoAreaId=&Location=San%20Felipe,%20Baja%20California,%20Mexico" page_scrape = requests.get(url) soup = BeautifulSoup(page_scrape.content, 'html.parser') lists = soup.find_all('article') for list_item in lists: # 避免用list作为变量名,和内置类型冲突 # 处理地址 address_elem = list_item.find('div', class_="address-container") address = address_elem.text.strip() if address_elem else "无地址信息" # 处理卧室数 beds_elem = list_item.find('li', class_="ic-beds") beds = beds_elem.text.strip() if beds_elem else "无卧室数据" # 处理浴室数 baths_elem = list_item.find('li', class_="ic-baths") baths = baths_elem.text.strip() if baths_elem else "无浴室数据" # 处理面积 size_elem = list_item.find('li', class_="ic-sqft") size = size_elem.text.strip() if size_elem else "无面积数据" # 处理房产类型 type_elem = list_item.find('li', class_="property-type ic-proptype") type = type_elem.text.strip() if type_elem else "无房产类型" # 处理价格 price_elem = list_item.find('span', class_="green") price = price_elem.text.strip() if price_elem else "无价格信息" # 处理代理名称 agent_elem = list_item.find('div', class_="agent-name") agent = agent_elem.text.strip() if agent_elem else "无代理名称" # 处理代理公司 firm_elem = list_item.find('div', class_="agent-company") firm = firm_elem.text.strip() if firm_elem else "无代理公司" info = [address, beds, baths, size, type, price, agent, firm] print(info)
关键改进点
- 避免使用
list作为循环变量名,防止和Python内置的list类型冲突 - 对每个字段先判断元素是否存在,再调用
.text,不存在时设置默认值替代报错 - 用
.strip()去除文本中的多余空格,让输出更整洁
内容的提问来源于stack exchange,提问作者Christopher Montoya
相关产品推荐
相关产品推荐

