combine code > 기타 Others

본문 바로가기


회원로그인

기타 Others

combine code

페이지 정보

Author 관리자1 쪽지보내기 메일보내기 자기소개 아이디로 검색 전체게시물 작성일25-02-12 21:21 조회 Read826회 댓글 Reply1건

본문

import os
import sys
import requests
from bs4 import BeautifulSoup
import re
from datetime import datetime
from urllib.request import urlopen
from tkinter import Tk, messagebox
from tkinter import ttk
from tkcalendar import Calendar


# Function to install missing modules
def install_missing_modules():
try:
import requests
from bs4 import BeautifulSoup
from tkcalendar import Calendar
except ImportError:
os.system(f"{sys.executable} -m pip install requests beautifulsoup4 tkcalendar")


# Check and install missing modules
install_missing_modules()


# Function to get a date from the user
def get_date_input():
def submit():
selected_date = calendar.get_date()
root.selected_date = selected_date
root.destroy()

root = Tk()
root.title("Select Date")
root.geometry("300x400")

# calendar = Calendar(root, date_pattern="yyyy-mm-dd")
# calendar.pack(pady=40)
# calendar_frame = ttk.Frame(root)
calendar = Calendar(
root,
date_pattern="yyyy-mm-dd",
font=("Arial", 16), # Bigger font size
foreground="black", # Font color for other dates
weekendforeground="blue", # Weekend color
headersbackground="lightgray", # Header background
selectforeground="red", # Selected date font color
)
calendar.pack(pady=40)

# calendar_frame = ttk.Frame(root)
# calendar = Calendar(
# calendar_frame,
# date_pattern="yyyy-mm-dd",
# font=("Arial", 16), # Bigger font size
# foreground="black", # Font color for other dates
# weekendforeground="blue", # Weekend color
# headersbackground="lightgray", # Header background
# selectforeground="red", # Selected date font color
# )
# calendar.pack(pady=40)



submit_button = ttk.Button(root, text="Submit", command=submit)
submit_button.pack(pady=40)

root.mainloop()
return getattr(root, "selected_date", None)


# Function to fetch content from the first source
def fetch_source_1(selected_date):
response = requests.get(url)

output_content = []
if response.status_code == 200:
soup = BeautifulSoup(response.text, "html.parser")

# Date
try:
script_content = soup.find("script", text=re.compile(r'\$\(\"\#base_de\"\)\.val\(".*?"\);')).string
match = re.search(r'\$\(\"\#base_de\"\)\.val\("(\d{4}-\d{2}-\d{2})"\);', script_content)
date = match.group(1) if match else "Date not found"
output_content.append(f"{date}\n")
except AttributeError:
output_content.append("Source 1 Date not found.\n")

# Title
try:
title = soup.find("div", class_="bible_text").get_text(strip=True)
output_content.append(f"{title}\n")
except AttributeError:
output_content.append("Title not found.\n")

# Bible Info
try:
bible_info = soup.find("div", class_="bibleinfo_box").get_text(strip=True)
output_content.append(f"{bible_info}\n")
except AttributeError:
output_content.append("Bible Info not found.\n")

# Verses
try:
verses = soup.find("ul", class_="body_list")
for verse in verses.find_all("li"):
verse_number = verse.find("div", class_="num").get_text(strip=True)
verse_text = verse.find("div", class_="info").get_text(strip=True)
output_content.append(f"{verse_number} {verse_text}\n")
except AttributeError:
output_content.append("Bible Verses not found.\n")
try:
body_content = soup.find("div", class_="body_cont")
if body_content:
# Extract b_text
b_text = body_content.find("div", class_="b_text")
if b_text:
output_content.append(f"\n요약: {b_text.get_text(strip=True)}\n")

# Extract g_text and text sections in sequence
commentary_sections = body_content.find_all("div", class_=["g_text", "text"])
for section in commentary_sections:
if "g_text" in section["class"]:
output_content.append(f"\n{section.get_text(strip=True)}\n")
elif "text" in section["class"]:
output_content.append(f"\n{section.get_text(strip=True)}\n")
else:
output_content.append("Commentary content not found.\n")
except AttributeError:
output_content.append("Error parsing commentary sections.\n")

return output_content


# Function to fetch content from the second source
def fetch_source_2(selected_date):

output_content = []

try:
# Fetch Korean content
# html_ko = urlopen(url_ko)
# soup_ko = BeautifulSoup(html_ko, "html.parser")
# output_content.append("\nSource 2 Korean Content:\n")
# for content in soup_ko.find_all("td", {"class": "padding"}):
# output_content.append(content.get_text(strip=True) + "\n")

# Fetch English content
html_en = urlopen(url_en)
soup_en = BeautifulSoup(html_en, "html.parser")
output_content.append("\n")
for content in soup_en.find_all('td', {"class": "padding"}):
output_content.append(content.get_text(strip=True) + "\n\n")
except Exception as e:
output_content.append(f"Error fetching Source 2: {e}\n")
# print(output_content)
return output_content
# # -----------

# Parse the HTML content
# html = urlopen(url_en)
# soup = BeautifulSoup(html, "html.parser")

# # Initialize extracted content
# extracted_content = []

# try:
# title = soup.find("td", {"align": "center", "style": "font-size: 26px;"}).get_text(strip=True)
# extracted_content.append(f"Title: {title}\n")
# except AttributeError:
# extracted_content.append("Title not found.\n")

# # Extract Bible verses
# try:
# verses = soup.find_all("div", style="text-indent:-22px;margin-left:13px;")
# if verses:
# extracted_content.append("\n")
# for verse in verses:
# extracted_content.append(verse.get_text(strip=True) + "\n")
# else:
# extracted_content.append("Bible verses not found.\n")
# except AttributeError:
# extracted_content.append("Error extracting Bible verses.\n")

# # Extract additional sections (like "Thinking & Understanding", "Who is God?", etc.)
# sections = soup.find_all("p", style="padding:15px;border:1px gray solid;background-color:#e4fcff;margin-bottom:30px;")
# if sections:
# for section in sections:
# title = section.find("span", style="color: #256F9C;font-weight:bolder;font-size:18px;")
# if title:
# extracted_content.append(f"\n{title.get_text(strip=True)}:\n")
# extracted_content.append(section.get_text(strip=True) + "\n")

# # Extract Prayer
# try:
# prayer = soup.find("td", {"style": "padding: 20px 0 0 0; font-size: 16px; line-height: 25px; font-family: Helvetica, Arial, sans-serif; color: #FFFFFF;"}).get_text(strip=True)
# extracted_content.append(f"\nPrayer:\n{prayer}\n")
# except AttributeError:
# extracted_content.append("Prayer not found.\n")

# return extracted_content
# # -----------


# Main function
def main():
selected_date = get_date_input()
if not selected_date:
print("No date selected. Exiting.")
return

# Fetch content from both sources
content_source_1 = fetch_source_1(selected_date)
content_source_2 = fetch_source_2(selected_date)

# Combine content
combined_content = ["\n"]
combined_content.extend(content_source_1)
combined_content.append("\n")
combined_content.extend(content_source_2)
# print(content_source_2)
# Write combined content to file
file_name = f"output_{selected_date}.txt"

if os.path.exists(file_name):
now = datetime.now().strftime("%Y%m%d_%H%M%S")
file_name = f"output_{now}.txt"
with open(file_name, "w", encoding="utf-8") as f:
f.writelines(combined_content)

# Notify and open the file
print(f"Output saved to {file_name}")
os.system(f"open {file_name}")


if __name__ == "__main__":
main()

 

 

wINDOWS

import os
import sys
import subprocess
import requests
from bs4 import BeautifulSoup
import re
from datetime import datetime
from urllib.request import urlopen
from tkinter import Tk, messagebox
from tkinter import ttk
from tkcalendar import Calendar


# Function to install missing modules
def install_missing_modules():
    required_modules = ["requests", "beautifulsoup4", "tkcalendar"]
    for module in required_modules:
        try:
            __import__(module)
        except ImportError:
            subprocess.check_call([sys.executable, "-m", "pip", "install", module])


# Check and install missing modules
install_missing_modules()


# Function to get a date from the user
def get_date_input():
    def submit():
        selected_date = calendar.get_date()
        root.selected_date = selected_date
        root.destroy()

    root = Tk()
    root.title("Select Date")
    root.geometry("320x450")  # Slightly increased height for better layout

    # Frame to center the calendar
    frame = ttk.Frame(root)
    frame.pack(expand=True, fill="both", padx=10, pady=10)

    calendar = Calendar(
        frame,
        date_pattern="yyyy-mm-dd",
        font=("Arial", 14),
        foreground="black",
        weekendforeground="blue",
        headersbackground="lightgray",
        selectforeground="red",
    )
    calendar.pack(expand=True, fill="both", padx=10, pady=10)

    # Submit button with better placement
    submit_button = ttk.Button(root, text="Submit", command=submit)
    submit_button.pack(side="bottom", pady=10)

    root.mainloop()
    return getattr(root, "selected_date", None)


# Function to fetch content from the first source
def fetch_source_1(selected_date):
    response = requests.get(url)

    output_content = []
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, "html.parser")

        # Date
        try:
            script_content = soup.find("script", text=re.compile(r'\$\(\"\#base_de\"\)\.val\(".*?"\);')).string
            match = re.search(r'\$\(\"\#base_de\"\)\.val\("(\d{4}-\d{2}-\d{2})"\);', script_content)
            date = match.group(1) if match else "Date not found"
            output_content.append(f"{date}\n")
        except AttributeError:
            output_content.append("Source 1 Date not found.\n")

        # Title
        try:
            title = soup.find("div", class_="bible_text").get_text(strip=True)
            output_content.append(f"{title}\n")
        except AttributeError:
            output_content.append("Title not found.\n")

        # Bible Info
        try:
            bible_info = soup.find("div", class_="bibleinfo_box").get_text(strip=True)
            output_content.append(f"{bible_info}\n")
        except AttributeError:
            output_content.append("Bible Info not found.\n")

        # Verses
        try:
            verses = soup.find("ul", class_="body_list")
            for verse in verses.find_all("li"):
                verse_number = verse.find("div", class_="num").get_text(strip=True)
                verse_text = verse.find("div", class_="info").get_text(strip=True)
                output_content.append(f"{verse_number} {verse_text}\n")
        except AttributeError:
            output_content.append("Bible Verses not found.\n")

    try:
        body_content = soup.find("div", class_="body_cont")
        if body_content:
            b_text = body_content.find("div", class_="b_text")
            if b_text:
                output_content.append(f"\n요약: {b_text.get_text(strip=True)}\n")

            commentary_sections = body_content.find_all("div", class_=["g_text", "text"])
            for section in commentary_sections:
                if "g_text" in section["class"]:
                    output_content.append(f"\n{section.get_text(strip=True)}\n")
                elif "text" in section["class"]:
                    output_content.append(f"\n{section.get_text(strip=True)}\n")
        else:
            output_content.append("Commentary content not found.\n")
    except AttributeError:
        output_content.append("Error parsing commentary sections.\n")

    return output_content


# Function to fetch content from the second source
def fetch_source_2(selected_date):

    output_content = []
    try:
        html_en = urlopen(url_en)
        soup_en = BeautifulSoup(html_en, "html.parser")
        output_content.append("\n")
        for content in soup_en.find_all('td', {"class": "padding"}):
            output_content.append(content.get_text(strip=True) + "\n\n")
    except Exception as e:
        output_content.append(f"Error fetching Source 2: {e}\n")

    return output_content


# Main function
def main():
    selected_date = get_date_input()
    if not selected_date:
        print("No date selected. Exiting.")
        return

    # Fetch content from both sources
    content_source_1 = fetch_source_1(selected_date)
    content_source_2 = fetch_source_2(selected_date)

    # Combine content
    combined_content = ["\n"]
    combined_content.extend(content_source_1)
    combined_content.append("\n")
    combined_content.extend(content_source_2)

    # Write combined content to file
    file_name = f"output_{selected_date}.txt"

    if os.path.exists(file_name):
        now = datetime.now().strftime("%Y%m%d_%H%M%S")
        file_name = f"output_{now}.txt"

    with open(file_name, "w", encoding="utf-8") as f:
        f.writelines(combined_content)

    # Notify and open the file
    print(f"Output saved to {file_name}")

    # Open file in a cross-platform way
    if sys.platform == "win32":
        os.system(f'start "" "{file_name}"')
    elif sys.platform == "darwin":
        os.system(f'open "{file_name}"')
    else:
        os.system(f'xdg-open "{file_name}"')


if __name__ == "__main__":
    main()

  • 페이스북으로 보내기
  • 트위터로 보내기
  • 구글플러스로 보내기

댓글목록 Reply List


교회소개 About Church 개인정보취급방침 Privacy Statement 서비스이용약관 Terms of Service Copyright © jiguchonchurch.org All rights reserved.
상단으로 To top

Southern Baptist Convention Arizona Global Baptist Church
536 E. Fillmore St., Tempe, AZ 85288 / T. (48O) 442-7329

모바일 버전으로 보기 Mobile Edition