Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在刮取数据时检查元素是否存在_Python_Web Scraping_Scrape - Fatal编程技术网

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语句后没有冒号(除非这是无意的),请不要检查元素是否存在。尝试使用它,然后在失败时捕获相应的错误。更准确地说,什么是数据刮取?什么是休息?