সমস্যা
একটি ওয়েব পেজ থেকে HTML টেবিল এক্সট্রাক্ট করতে হবে।
ভূমিকা
ইন্টারনেট আজকার সবচেয়ে বড় তথ্যের সোর্স। এই তথ্য প্রোগ্রামেটিক্যালি রিট্রিভ এবং প্রসেস করা যায়। পাইথনের স্ট্যান্ডার্ড লাইব্রেরিতে HTTP ক্লায়েন্ট আছে, কিন্তু requests মডিউল অনেক সহজ করে দেয়। এখানে আমরা দেখব HTML পেজ পার্স করে এমবেডেড টেবিল বের করা।
কীভাবে করবেন
১. প্যাকেজ ইম্পোর্ট
import requests
import pandas as pd
from tabulate import tabulate
২. টার্গেট URL এবং রিকোয়েস্ট
site_url = "https://www.tutorialspoint.com/python/python_basic_operators.htm"
response = requests.get(site_url)
print(f"The response for {site_url} is {response.status_code}")
৩. হেডার এবং কন্টেন্ট চেক
print(response.request.headers)
print(response.headers)
print(response.text[:100])
৪. BeautifulSoup দিয়ে HTML পার্স
from bs4 import BeautifulSoup
tutorialpoints_page = BeautifulSoup(response.text, 'html.parser')
print(tutorialpoints_page.title.string)
৫. হেডিং ট্যাগ (h2-h6) খুঁজে বगलের টেবিল বের করুন
tags = tutorialpoints_page.find(lambda elm: elm.name in ["h2","h3","h4","h5","h6"])
for sibling in tags.find_next_siblings():
if sibling.name == "table":
my_table = sibling
df = pd.read_html(str(my_table))
print(tabulate(df[0], headers='keys', tablefmt='psql'))
৬. সম্পূর্ণ কোড
import requests
import pandas as pd
from bs4 import BeautifulSoup
from tabulate import tabulate
site_url = "https://www.tutorialspoint.com/python/python_basic_operators.htm"
response = requests.get(site_url)
print(f"Response: {response.status_code}")
tutorialpoints_page = BeautifulSoup(response.text, 'html.parser')
print(f"Page title: {tutorialpoints_page.title.string}")
tags = tutorialpoints_page.find(lambda elm: elm.name in ["h2","h3","h4","h5","h6"])
for sibling in tags.find_next_siblings():
if sibling.name == "table":
my_table = sibling
df = pd.read_html(str(my_table))
print(tabulate(df[0], headers='keys', tablefmt='psql'))
আউটপুট
পেজের সব টেবিল প্রিন্ট হয় (অপারেটর টাইপ, ডেসক্রিপশন, উদাহরণ ইত্যাদি)।