【发布时间】:2021-10-01 22:54:48
【问题描述】:
我正在尝试使用 Python-Selenium 从该网站https://ricetta.it/ricette-secondi 抓取所有数据。
我想将它们放入字典中,如下面的代码所示。 但是,这只是返回一个空列表。
import pprint
detail_recipes = []
for recipe in list_recipes:
title = ""
description = ""
ingredient = ""
if(len(recipe.find_elements_by_css_selector(".post-title")) > 0):
title = recipe.find_elements_by_css_selector(".post-title")[0].text
if(len(recipe.find_elements_by_css_selector(".post-excerpt")) > 0):
description = recipe.find_elements_by_css_selector(".post-excerpt")[0].text
if(len(recipe.find_elements_by_css_selector(".nm-ingr")) > 0):
ingredient = recipe.find_elements_by_css_selector(".nm-ingr")[0].text
detail_recipes.append({'title': title,
'description': description,
'ingredient': ingredient
})
len(detail_recipes)
pprint.pprint(detail_recipes[0:10])
【问题讨论】:
-
my code解决了您的问题吗?我已经为您提供了有关这些库的更多信息,如果您不熟悉该库,那么这将非常有帮助。如果解决了,请不要忘记将其标记为已接受的答案。如果有任何疑问,请在评论中提问。
-
谢谢,你的代码很完美。但我无法将数据保存在 CSV 文件中。事实上,当我写: df.to_csv("
") 我得到: 'dict' object has no attribute 'to_csv' -
你忘了写
df=pd.DataFrame(df) df.dropna(axis=0,inplace=True)两行:) -
非常感谢!最后一件事:我还想抓取每个标题的链接。我怎样才能得到它们?
-
我已经编辑了答案。检查那个。如果你喜欢我的努力,请给我的答案投票。
标签: python selenium web-scraping css-selectors