Переход к папке с HTML файлов и выполнение предопределенной функции для каждого файла - PullRequest
0 голосов
/ 26 мая 2020

Я все еще новичок в программировании. Мне нужно было написать код для перебора папки с данными из многих html файлов и выполнения предопределенной функции (Извлечение определенных c таблиц из HTML документа). Я использовал bs4 для анализа файла html. Предлагаемое ниже решение позволяло извлекать файлы и извлекать таблицы из каждого html файла.

from bs4 import BeautifulSoup
import glob

def get_soup(html_file_path):  
    f = html_file_path.open()
    return BeautifulSoup(f, "lxml")

def get_all_tables(soup):
    return soup.find_all("table")

def get_all_html_files(root_path):
    return Path(root_path).glob("**/*.html")

if __name__ == "__main__":
    html_root = Path("data_file_pathname/")

    soup = get_soup(html_file)

    tables = get_all_tables(soup)
    print(f"[+] Found a total of {len(tables)} tables.")


Спасибо

1 Ответ

0 голосов
/ 26 мая 2020

Вы можете использовать функцию Path.glob из стандартного библиотечного модуля pathlib .

Например:

from pathlib import Path

def get_soup(html_file_path):  # added argument
    f = html_file_path.open()
    return BeautifulSoup(f, "lxml")

def get_all_tables(soup):
    return soup.find_all("table")

def get_all_html_files(root_path):
    return Path(root_path).glob("**/*.html")

if __name__ == "__main__":
    html_root = Path("./html_files/")  # This is the folder with the html files

    for html_file in get_all_html_files(html_root):
        soup = get_soup(html_file)
        tables = get_all_tables(soup)
...