Хочу правильно преобразовать парсер Python в JSON, но как это сделать

Рейтинг: 3Ответов: 1Опубликовано: 09.03.2023

Я бы с удовольствием хотел узнать, как правильно осуществить конвертацию кода Python в массив JSON? При всём при этом нужно, чтобы всё определялось в этом коде автоматически. Можно сказать, что здесь должен играть свою роль бот JSON, который бы автоматически выделял надписи из сайта в свой код.

import re
import time
from urllib.parse import quote, unquote
from urllib.request import urlopen 
import requests
from bs4 import BeautifulSoup
url = "https://fasie.ru"
page = urlopen(url)
html = page.read().decode("utf-8")
soup = BeautifulSoup(html, "html.parser")
div = soup.find_all('div', class_ = 'wrap')
programms_list = div[1].find('ul', class_='').find_all('ul', class_='')[1]
hrefs = programms_list.find_all('a')
download_links = set()
response = requests.get(url+'/programs')
parse_text = BeautifulSoup(response.text, 'html.parser')
links = set([x.get('href') for x in parse_text.find_all(href=re.compile('^/programs/'))])
def main():
    for h in hrefs:
        url_h = f"https://fasie.ru{h.get('href')}"
        page_h = urlopen(url_h)
        html_h = page_h.read().decode("utf-8")
        soup_h = BeautifulSoup(html_h, "html.parser")
        sections = soup_h.find_all('section')
        for s in sections:
            print(s.text)
    for link in links:
        response = requests.get(url+link)
        parse_text = BeautifulSoup(response.text, 'html.parser')
        download_links.update(set([x.get('href') for x in parse_text.find_all(href=re.compile('^/upload/docs'))]))
        for link in download_links:
            file_name = unquote(link).split('/')[-1]
            response = requests.get(url+quote(link))
            with open(file_name, 'wb') as f:
                f.write(response.content)
main()

Здесь описано, каким образом должен выглядеть JSON

[
  {
    "source": "Ссылка, откуда взята информация", // в данном случае ссылка fasie.ru
    "name": "ИнноШкольник",
    "description": "Информация из вкладки `О программе`",
    "program": "Данные из вкладки `Конкурсы, программы` в формате HTML",
    "contacts": [
      {
        "name": "Имя контакта",
        "tel": "Телефон",
        "email": "Почта контакта"
      }
    ],
    "documents": [
      {
        "source": "Ссылка на файл оригинальная, т.е откуда скачали",
        "path": "Относительный путь к файлу (уже скачанного)",
        "name": "Название файла",
        "extension": "Расширение файла (напр. pdf)",
        "size": 123 // Размер в байтах
      }
    ]
  }
]

В общем, мне нужно, чтобы был вывод в JSON. Но нужно, чтобы этим занялся бот, который находит с сайта нужную информацию (имя, контакты и т.д.) и выводил это в базу данных JSON. Как показано на превьюхе.

Ответы

▲ 4Принят

Попробуйте такой код

import json
import re
import time
from urllib.parse import quote, unquote
from urllib.request import urlopen 
import requests
from bs4 import BeautifulSoup

url = "https://fasie.ru"
page = urlopen(url)
html = page.read().decode("utf-8")
soup = BeautifulSoup(html, "html.parser")
div = soup.find_all('div', class_ = 'wrap')
programms_list = div[1].find('ul', class_='').find_all('ul', class_='')[1]
hrefs = programms_list.find_all('a')
download_links = set()
response = requests.get(url+'/programs')
parse_text = BeautifulSoup(response.text, 'html.parser')
links = set([x.get('href') for x in parse_text.find_all(href=re.compile('^/programs/'))])

programs = []

def main():
    for h in hrefs:
        program = {}
        program['source'] = url
        program['name'] = h.text.strip()
        url_h = f"https://fasie.ru{h.get('href')}"
        page_h = urlopen(url_h)
        html_h = page_h.read().decode("utf-8")
        soup_h = BeautifulSoup(html_h, "html.parser")
        description = soup_h.find('section', {'class': 'info-block'})
        program['description'] = description.text.strip() if description else ''
        program['program'] = str(soup_h.find('section', {'class': 'project-block'}))

        contacts = []
        contacts_section = soup_h.find('section', {'class': 'contact-block'})
        if contacts_section:
            contact_items = contacts_section.find_all('li')
            for contact in contact_items:
                contact_dict = {}
                contact_dict['name'] = contact.find('span', {'class': 'contact-title'}).text.strip()
                contact_dict['tel'] = contact.find('span', {'class': 'contact-tel'}).text.strip()
                contact_dict['email'] = contact.find('a', {'class': 'contact-email'}).text.strip()
                contacts.append(contact_dict)
        program['contacts'] = contacts

        sections = soup_h.find_all('section')
        documents = []
        for s in sections:
            download_links.update(set([x.get('href') for x in s.find_all(href=re.compile('^/upload/docs'))]))
        for link in download_links:
            file_name = unquote(link).split('/')[-1]
            response = requests.get(url+quote(link))
            with open(file_name, 'wb') as f:
                f.write(response.content)
            document = {}
            document['source'] = url+link
            document['path'] = file_name
            document['name'] = file_name
            document['extension'] = file_name.split('.')[-1]
            document['size'] = len(response.content)
            documents.append(document)
        program['documents'] = documents
        programs.append(program)
    with open('output.json', 'w') as f:
        f.write(json.dumps(programs, indent=2))

main()