Python 在刮取数据时检查元素是否存在
我试图从一些餐馆的开放式表格中获取评论,但由于其中一些餐馆没有评论,我得到了一个打字错误 我目前的代码是:Python 在刮取数据时检查元素是否存在,python,web-scraping,scrape,Python,Web Scraping,Scrape,我试图从一些餐馆的开放式表格中获取评论,但由于其中一些餐馆没有评论,我得到了一个打字错误 我目前的代码是: ratings = restDOM.by_id("RestPopLabel_ReviewsFormat")[0].attributes ratings = ratings['title'] 我试着做一些类似的事情: if restDOM.by_id("RestPopLabel_ReviewsFormat")[0] is present ratings = restDOM.by_i
ratings = restDOM.by_id("RestPopLabel_ReviewsFormat")[0].attributes
ratings = ratings['title']
我试着做一些类似的事情:
if restDOM.by_id("RestPopLabel_ReviewsFormat")[0] is present
ratings = restDOM.by_id("RestPopLabel_ReviewsFormat")[0].attributes
ratings = ratings['title']
else
ratings = 'not available'
实现if语句的最佳方法是什么?Ben的答案在这里是正确的,但我想我应该用实际代码展开:
try:
ratings = restDOM.by_id("RestPopLabel_ReviewsFormat")[0].attributes
ratings = ratings['title']
except KeyError:
ratings = 'not available'
如果您应该得到一个
SyntaxError
,因为If/else语句后没有冒号(除非这是无意的),请不要检查元素是否存在。尝试使用它,然后在失败时捕获相应的错误。更准确地说,什么是数据刮取?什么是休息?