0

В общем, суть такова. Мне нужно скачать из сайта https://fasie.ru/ документы. Они могут быть в любом формате: pdf или doc. Мне нужно скачать всех форматов. Однако, нужно, чтобы парсинг был автоматический. То есть, чтобы можно было скачать из всех страниц сайта, где есть документа, при этом нельзя писать ссылки на этот сайт в коде. Всё должно быть автоматически сгенерированно.

Вот код:

from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import webbrowser
import urllib
import urllib.request
import os
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
from urllib.request import urlretrieve

#Need to download from all pages that has a files and page "/#documentu"
#but without writing all links in code. It must be an automatic.
urlpage = "https://fasie.ru/programs/programma-innoshkolnik/#documentu"


#If there is no such folder, the script will create one automatically
folder_location = r'C:\Download'
if not os.path.exists(folder_location):os.mkdir(folder_location)

response = requests.get(urlpage)
soup= BeautifulSoup(response.text, "html.parser")     
for link in soup.select("a[href$='.pdf']"):
    #Name the pdf files using the last portion of each link which are unique in this case
    filename = os.path.join(folder_location,link['href'].split('/')[-1])
    with open(filename, 'wb') as f:
        f.write(requests.get(urljoin(urlpage,link['href'])).content)
path = r'C:\Download'
i = 1
for file_name in os.listdir(path):
    base_name, ext = os.path.splitext(file_name)
    abs_file_name = os.path.join(path, file_name)
    new_abs_file_name = os.path.join(path, str(i) + ext)
    os.rename(abs_file_name, new_abs_file_name)
    i += 1

Документы хранятся в основном в разделе "#documentu". Но нужно, чтобы опять же, полностью ссылка не выводилась. Как сделать так, чтобы скачивались документы из всех страниц, где есть раздел "#documentu"?

2

1 ответ 1

0

Хоть я написал этот код давно, всё же оставлю его тут. Просто потому что мне нужно ради повышения репутации.

import requests
from bs4 import BeautifulSoup
import re
import os
from urllib.request import urlopen
import json
from urllib.parse import unquote

class Parser:

    def __init__(self, href) -> None:
        self.url = "https://fasie.ru"
        self.href = href
        self.source = self.url + self.href['href']
        self.name = self.href.text
        try:
            r = requests.get(self.source, timeout=20)
        except:
            print(f'err. conn: {self.source} in "def __init__"')
        soup = BeautifulSoup(r.text, "html.parser")
        self.section = soup.find('div',{'class':'tabs'}).find_all('section')

    def get_description(self):
        l = re.findall(r"[^\n\t\r]+", self.section[2].text)
        return '\n'.join(map(str.strip, l))
        
    def get_program(self):
        l = re.findall(r"[^\n\t\r]+", self.section[0].text)
        return '\n'.join(map(str.strip, l))

    def get_contact(self):
        l = []
        pattern = r"(\+?[\d\(\) -]+)\s\(?доб\.\s?\d{3}\)?"
        pattern_email = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b"
        if self.section[-1].find('tr'):
            for i in self.section[-1].find_all('tr'):
                d = {}
                d['name'] = i.find('h4').text.strip().replace('\xa0', ' ').split('\r', 1)[0]
                tmp = re.search(pattern, i.text)
                d['tel'] = tmp[1] if tmp else ''
                tmp = re.search(pattern_email, i.text)
                d['email'] = tmp[0] if tmp else ''
                if sum(map(len, d.values())): 
                    l.append(d)
        elif self.section[-1].find('b'):
            name = [i.text for i in self.section[-1].find_all('b') if i.text.strip()]
            tel = re.findall(pattern, self.section[-1].text)
            email = [i.text for i in self.section[-1].find_all('a') if i.text]
            for i in zip(name, tel, email):
                d = {}
                d['name'] = i[0].strip().replace('\xa0', ' ')
                d['tel'] = re.sub(r'\s\(?доб\.\s?\d{3}\)', '', i[1].strip())
                d['email'] = i[2].strip()
                l.append(d)
        else:
            for i in self.section[-1].find_all('p', recursive=False):
                if i.find('a'):
                    d = {}
                    d['name'] = ''
                    tmp = re.search(pattern, i)
                    d['tel'] = tmp[0] if tmp else ''
                    d['email'] = i.find('a').text
                    l.append(d)
        return l

    def get_documents(self):
        l = []
        for i in self.section[1].find_all('a'):
            if i['href']:
                i['href'] = i['href'].replace(self.url, '')
                name = unquote(i['href'])
                d = {}
                d['source'] = self.url + '/' + i['href'].lstrip('/')
                d['path'] = f"./{self.href['href'].strip('/')}/{name}"
                d['name'] = name.rsplit('/', 1)[-1]
                d['extension'] = name.rsplit('.', 1)[-1]
                try:
                    r = requests.get(d['source'], timeout=20)
                except:
                    print(f"err. conn: {d['source']}")
                    continue
                if r.status_code == 200:
                    try:
                        os.makedirs(os.path.dirname(d['path']), exist_ok=True)
                    except:
                        print(f"Ошибка при создание папки\nТег: {i}\nname{d['path']}")
                        raise
                    try:
                        with open(d['path'], 'wb') as f:
                            f.write(r.content)
                    except:
                        print(f"Ошибка при создание файла\nТег: {i}")
                        raise
                    d['size'] = len(r.content)
                    l.append(d)
                else:
                    print(f"{d['source']} no response")
        return l
    
    def run(self):
        d = {
            'source':self.source,
            'name':self.name,
            'description':self.get_description(),
            'programs':self.get_program(),
            'contacts':self.get_contact(),
            'documents':self.get_documents()
        }
        return d


def main():
    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')
    data = []
    for i in hrefs:
        p = Parser(i)
        data.append(p.run())

    with open('output.json', 'w', encoding="utf-8") as f:
        f.write(json.dumps(data, indent=2, ensure_ascii=False))

main()

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

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