python - Webscraping:在循环中用 0 替换 None 值
问题描述
我是构建房屋网络刮板的初学者。我正在构建不同的函数来提取不同的数据(价格、网址、图像、卧室等)
我对卧室有疑问,因为有些房源没有列出卧室。可能是一块土地,或者他们忘记了卧室的数量。当代码遍历列表中的所有卧室时,如果它没有卧室,这是我收到的错误消息:
Traceback (most recent call last):
File "get_address.py", line 27, in <module>
print(get_bedrooms())
File "get_address.py", line 17, in get_bedrooms
html_bedrooms = listing.find('h3', {'class': 'listing-results-attr'}).find('span', {'class': 'num-beds'})
AttributeError: 'NoneType' object has no attribute 'find'
这是代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
html = urlopen('https://www.zoopla.co.uk/for-sale/property/london/')
bs = BeautifulSoup(html, 'html.parser')
def get_bedrooms():
bedrooms = []
# Finds all the listings_<id> using a regular expression
for listing in bs.find_all('li', id=re.compile(r'listing.[0-9]+')):
# Finds this code <span class="num-icon num-beds" title="2 bedrooms"><span class="interface"></span>2</span> and stores it in html_bedroom
html_bedrooms = listing.find('h3', {'class': 'listing-results-attr'}).find('span', {'class': 'num-beds'})
# Extracts the text in the span tags
no_of_bedrooms = html_bedrooms.get_text(strip=True)
# Updates the empty list with number of bedrooms
bedrooms.append(no_of_bedrooms)
return bedrooms
print(get_bedrooms())
如何检查是否有无类型值,然后将其替换为 0?
解决方案
你可以使用这个:
[0 if x is None else x for x in listing]
将返回另一个列表,其中 None 被替换为 0。
推荐阅读
- php - 如何在 Laravel 7 导出中获取变量值?
- python - Python:如何自动更新数组中的引用元素?
- plot - 可以用 jsxgraph 制作波特图
- javascript - 更新 TinyMce 模板插件
- flutter - 如何使用 GetX 包获取 Flutter 中的当前语言环境?
- html - 如何将 h5 元素移动到 div 的左上角?
- javascript - 反应对象和数组
- css - 在 CSS 预处理器中使用属性作为变量?
- excel - 当我将变量函数“cells(i,3)”添加到“Filter”时,运行时错误 440 无法解析
- ubuntu - 乌尔都语和信德语缺少几个字符