0

Пытаюсь вывести переменную items через команду бота, но она не определяется. Как решить?

import requests
from bs4 import BeautifulSoup
import discord
from discord.ext import commands
from discord.ext.commands import Bot


Bot = commands.Bot(command_prefix= '!')
client = discord.Client()

URL = 'site'
HEADERS = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36', 'accept': '*/*'}

def get_html(url, params=None):
    r = requests.get(url, headers=HEADERS, params=params)
    return r

def get_content(html):
    soup = BeautifulSoup(html, 'html.parser')
    items = soup.find_all('div', class_='player-name')

    print(items)



def parse():
    html = get_html(URL)
    if html.status_code == 200:
        get_content(html.text)


parse()

@Bot.command(pass_context = True)
async def code(ctx):
    html = get_html(URL)
    await ctx.send(html)

Bot.run('--------------')
6
  • А почему из get_content не возвращаете items?
    – gil9red
    28 ноя 2020 в 19:13
  • Возвратил: ~~~ def get_content(html): soup = BeautifulSoup(html, 'html.parser') items = soup.find_all('div', class_='player-name') return items def parse(): html = get_html(URL) if html.status_code == 200: get_content(html.text) parse() @Bot.command(pass_context = True) async def code(ctx): html = get_html(URL) await ctx.send(get_content(items)) ~~~ Но результата не принесло, та же ошибка: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'items' is not defined
    – Sterof
    28 ноя 2020 в 19:36
  • Для parse аналогично, раз она вызывает get_content, то ей или его обработать, или вернуть, чтобы там где parse будет вызвана получить результат. И вы явно не весь код привели, т.к. в текущем явно не будет ошибки с items. Вообще, items существует только внутри функции, поэтому ее нужно вернуть из функции, чтобы ее значение стало доступно извне
    – gil9red
    28 ноя 2020 в 19:40
  • Ещё не понял как тут форматирование кода в комментарии сделать, кину скриншотом. cdn.discordapp.com/attachments/719968531420020743/… Формально items я вернул в get_content, но вызвать его не получается.
    – Sterof
    28 ноя 2020 в 19:47
  • Под вопросом есть кнопка править ею и добавляйте код в вопрос. Форматировать код можно через {} на панели в редакторе или добавляя ``` до и после кода. Почему у вас в строке с ошибкой в скрине передается в функцию get_content не html, а items?
    – gil9red
    28 ноя 2020 в 20:03

1 ответ 1

0

Подправил код из вопроса и теперь items будет передано в ctx.send. Места, где изменил, выделил

Но есть вопрос: понимает ли ctx.send значение из items? А это результат выполнения soup.find_all, что, является списком элементов Tag из bs4. Возможно, нужно будет обработать items, чтобы, например, получить строку.

Код:

import requests
from bs4 import BeautifulSoup
import discord
from discord.ext import commands
from discord.ext.commands import Bot


Bot = commands.Bot(command_prefix= '!')
client = discord.Client()

URL = 'site'
HEADERS = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36', 'accept': '*/*'}

def get_html(url, params=None):
    r = requests.get(url, headers=HEADERS, params=params)
    return r

def get_content(html):
    soup = BeautifulSoup(html, 'html.parser')
    items = soup.find_all('div', class_='player-name')
    return items
    # ^^^^^^^^^^^^^^^^^

def parse():
    r = get_html(URL)
    r.raise_for_status()
    return get_content(r.content)
    # ^^^^^^^^^^^^^^^^^


@Bot.command(pass_context = True)
async def code(ctx):
    items = parse()
    await ctx.send(items)
    # ^^^^^^^^^^^^^^^^^

Bot.run('--------------')
2
  • Всё заработало как нужно, буду разбираться как и где накосячил) Спасибо.
    – Sterof
    28 ноя 2020 в 21:55
  • @Sterof, пожалуйста :)
    – gil9red
    28 ноя 2020 в 22:20

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.