【问题标题】:How to append multiple value in csv file header with python如何使用python在csv文件头中附加多个值
【发布时间】:2022-10-25 23:03:13
【问题描述】:

这是我的代码,我无法在“标题、成分、说明、营养素、图片、链接”中附加值

from recipe_scrapers import scrape_me
import requests
from recipe_scrapers import scrape_html
from csv import writer



with open('recipe.csv', 'w', encoding='utf8', newline='') as file:

    #create new CSV file and write header that name Title ,Ingredients,instructions,nutrients,Image,link.
    thewriter = writer(file)
    header = ['Title', 'Ingredients', 'Instructions', 'Nutrition_Facts','image','links']
    thewriter.writerow(header)


url = "https://www.allrecipes.com/recipe/220751/quick-chicken-piccata/"
html = requests.get(url).content
scraper = scrape_html(html=html, org_url=url)

for scrap in scraper:
    #this loop add Title ,Ingredients,instructions,nutrients,Image,link value .
    info = ['title, Ingredients, instructions, nutrients,Image,link']
    thewriter.writerow(info)

    Title = scraper.title()
    Ingredients = scraper.ingredients()
    instructions = scraper.instructions()
    nutrients = scraper.nutrients()
    Image = scraper.image()
    link = scraper.links()
print(scrap)

我如何解决此代码

【问题讨论】:

  • 欢迎来到 SO。你能更清楚一点,你在哪里有问题吗?

标签: python export-to-csv


【解决方案1】:

您的代码存在许多问题。首先,您的缩进已关闭。您在不同的代码块中创建 thewriter 变量,然后尝试在不同的代码块中访问它。要解决此问题,您必须将 with open 语句下方的所有代码缩进到同一级别。

其次,根据recipe-scrapers docscraper 是一个不能迭代的AllRecipesCurated 对象,所以你的行:

for scrap in scraper:

没有意义,因为您尝试迭代不可迭代的对象并会给您一个错误。

最后,这两行:

info = ['title, Ingredients, instructions, nutrients,Image,link']
thewriter.writerow(info)

意味着您将始终将标题写入文件,而不是从调用 URL 获得的数据。相反,您应该让它指向您从 url 中提取的数据:

thewriter.writerow([scraper.title(), scraper.ingredients(), scraper.instructions(), scraper.nutrients(), scraper.image(), scraper.links()])

这是修复的完整代码。您应该能够使用它获得正确的结果:

import requests
from recipe_scrapers import scrape_html
from csv import writer

with open('recipe.csv', 'w', encoding='utf8', newline='') as file:
    # create new CSV file and write header that name Title ,Ingredients,instructions,nutrients,Image,link.
    thewriter = writer(file)
    header = ['Title', 'Ingredients', 'Instructions', 'Nutrition_Facts', 'image', 'links']
    thewriter.writerow(header)

    url = "https://www.allrecipes.com/recipe/220751/quick-chicken-piccata/"
    html = requests.get(url).content
    scraper = scrape_html(html=html, org_url=url)

    thewriter.writerow([scraper.title(), scraper.ingredients(), scraper.instructions(), scraper.nutrients(), scraper.image(), scraper.links()])

【讨论】:

    猜你喜欢
    • 2015-11-23
    • 2018-05-16
    • 2019-06-07
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多