Как сделать действие для каждого результата в массиве? - PullRequest
0 голосов
/ 01 мая 2020

Я пытаюсь очистить некоторые рецепты, используя рецепт-скребки и Python. В приведенном ниже коде я пытаюсь добавить несколько URL, чтобы очистить и в конце получить данные в файл CSV. Код также проверяет, находится ли домен в списке поддерживаемых сайтов. К сожалению, это не работает.

Отображается ошибка:

AttributeError: 'list' object has no attribute 'decode'

Я думаю, что это потому что код неправильный,

domain = urlparse(site).netloc

нарушает все это.

Однако он работает только с одним доменом сайта.

import csv
from recipe_scrapers import scrape_me, SCRAPERS
from urllib.parse import urlparse

site = ['https://www.website.com/recipe/246439/poulet--poulet-solange',
        'https://www.website.com/recipe/244688/-dauphinois-white-vin/?',
        'https://www.website.com/recipe/223506/--white/']

if site != '':

    for i in site:
        # Now check to see if the domain is in the SCRAPERS dictionary...
        domain = urlparse(site).netloc
        domain = domain.replace("www.", "")
        if domain in SCRAPERS:

           scraper = scrape_me(site)
           title = scraper.title()
           total_time = scraper.total_time()
           yields = scraper.yields()
           ingredients = scraper.ingredients()
           instructions = scraper.instructions()
           image = scraper.image()

           #print(f'Title: {title}')
           #print(f'Total Time: {total_time}')
           #print(f'Servings: {yields}')
           # print(f'Ingredients: {ingredients}')
           #print('Ingredients:\n')
           #for ing in ingredients:
           #    print(f'    {ing}')
           #print(f'\nInstructions: {instructions}')
           #print(f'Image URL: {image}')
        #else:
             #print('\nSorry, that website is not currently supported.')
             # to do : export data to csv . change words/synonyms. Re-export csv to create wordpress posts

with open('test.csv', "w", encoding="utf-8") as recipes_file:
    for i in site :
        recipe_writer = csv.writer(recipes_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        recipe_writer.writerow([title, total_time, ingredients, instructions, image])

1 Ответ

2 голосов
/ 01 мая 2020

Может быть, я что-то упускаю, но, насколько я понимаю, вам просто нужно использовать i вместо site (вы в конце концов просматриваете список сайтов).

domain = urlparse(site).netloc и scraper = scrape_me(site) как минимум.

РЕДАКТИРОВАТЬ:

В дополнение к вашему комментарию - вы фактически сохраняете последний результат 3 раза, так как вы делаете его в отдельном для l oop , Чтобы это исправить, можно реструктурировать код и поместить все в один для l oop:

Перед тем, как запустить l oop:
with open('test.csv', "w", encoding="utf-8") as recipes_file:

Inside l oop:
recipe_writer = csv.writer(recipes_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
recipe_writer.writerow([title, total_time, ingredients, instructions, image])

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...