运行此代码时,所有操作都正常,但是输出没有写入CSV文件。我的data.txt文件包含一些链接。
import csv
import requests
from recipe_scrapers import scrape_html
from csv import writer
with open('recipe.csv', 'w', encoding='utf8', newline='') as file:
thewriter = writer(file)
header = ['Title', 'Ingredients', 'Instructions', 'Nutrition_Facts', 'image', 'links']
thewriter.writerow(header)
with open('data.txt', 'r') as inf:
for line in inf:
html = requests.get(line).content
scraper = scrape_html(html=html, org_url=line)
thewriter.writerow([scraper.title(), scraper.ingredients(), scraper.instructions(), scraper.nutrients(), scraper.image(), scraper.links()])发布于 2022-09-17 15:27:25
如果代码的缩进如您所示,您只会将头写入输出文件,循环输入,然后只尝试从最后一个刮板再写一行,但即使是在退出with块时输出文件被关闭之后。
将最后一行缩进与scraper = ...相同的级别,否则不可能正常工作。如下所示:
with open('recipe.csv', 'w', encoding='utf8', newline='') as file:
thewriter = writer(file)
...
with open('data.txt', 'r') as inf:
for line in inf:
html = requests.get(line).content
scraper = scrape_html(html=html, org_url=line)
thewriter.writerow([.....]) # <---- proper indent发布于 2022-09-17 16:51:26
我会尝试重新安排逻辑,使之更有秩序。在将来调试代码时,这可能会有所帮助。
正如alexis所指出的,您的问题是不适当的缩进,导致了范围问题。我将重温您选择的一些关于Python范围的培训材料。
from csv import writer
import requests
from recipe_scrapers import scrape_html
with open('recipe.csv', 'w', encoding='utf8', newline='') as file:
thewriter = writer(file)
thewriter.writerow(['Title', 'Ingredients', 'Instructions', 'Nutrition_Facts', 'image', 'links']) # Header
with open('data.txt', 'r') as inf:
for line in inf:
html = requests.get(line).content
scraper = scrape_html(html=html, org_url=line)
thewriter.writerow([scraper.title(), scraper.ingredients(), scraper.instructions(), scraper.nutrients(), scraper.image(), scraper.links()])https://stackoverflow.com/questions/73756096
复制相似问题