import re
from bs4 import BeautifulSoup
from openpyxl import Workbook
from datetime import datetime
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.utils import get_column_letter
Read the content from the .txt file
with open('combined_source_code.txt', 'r', encoding='utf-8') as file:
content = file.read()
data = []
for post in posts:
# Extract Post Name (Tiêu đề bài viết)
post_title_div = post.find('div', class_='post_title')
if post_title_div:
post_title = post_title_div.text.strip()
else:
continue # Skip if no title found
code
# Extract Keyword (Từ khóa chính của bài viết)
input_focus_keyword = post.find('input', {'data-field': 'focus_keyword'})
if input_focus_keyword:
keyword = input_focus_keyword.get('value', '').strip()
else:
keyword = ''
# Extract Link (Đường dẫn bài viết)
view_link = None
row_actions = post.find('div', class_='row-actions')
if row_actions:
view_action = row_actions.find('span', class_='view')
if view_action and view_action.find('a'):
view_link = view_action.find('a')['href']
# Extract Date (Ngày đăng/Ngày dự kiến)
date_td = post.find('td', class_='date column-date')
if date_td:
date_text = date_td.get_text(separator=' ').strip()
# Extract date using regex
match = re.search(r'(\d{2}/\d{2}/\d{4} lúc \d{1,2}:\d{2} (chiều|sáng))', date_text)
if match:
date_published = match.group(1)
else:
date_published = ''
else:
date_published = ''
# Append to data list
data.append({
'Tiêu đề bài viết': post_title,
'Từ khóa chính của bài viết': keyword,
'Đường dẫn bài viết': view_link,
'Ngày đăng/Ngày dự kiến': date_published
})
Assistant
Create an Excel workbook and select the active worksheet
wb = Workbook()
ws = wb.active
Set the font for the entire worksheet to Times New Roman
for row in ws.iter_rows():
for cell in row:
cell.font = Font(name='Times New Roman')
Merge cells A1 to D1 and format
ws.merge_cells('A1:F1')
today_str = datetime.today().strftime('%d/%m/%Y')
ws['A1'] = f"Báo cáo An Nhiên Group Hòa Bình ngày {today_str} (Long)"
ws['A1'].font = Font(name='Times New Roman', size=20, bold=True)
ws['A1'].alignment = Alignment(horizontal='center')
Set cell A3 with specified text
ws['A3'] = f"1. Bài viết đã đăng (Đăng bài viết ngày {today_str})"
ws['A3'].font = Font(name='Times New Roman', size=15, bold=True)
Set headers starting from row 4
headers = [
'Tiêu đề bài viết',
'Từ khóa chính của bài viết',
'Đường dẫn bài viết',
'Ngày đăng/Ngày dự kiến',
'Người đăng bài',
'Ngày viết'
]
header_row = 4
for col_num, header in enumerate(headers, 1):
cell = ws.cell(row=header_row, column=col_num, value=header)
cell.font = Font(name='Times New Roman', bold=True)
cell.fill = PatternFill(start_color='FFE4D5', end_color='FFE4D5', fill_type='solid')
Adjust column widths
column_widths = [40, 30, 50, 25, 20, 15]
for i, width in enumerate(column_widths, 1):
ws.column_dimensions[get_column_letter(i)].width = width
Add extracted data to the worksheet
current_row = header_row + 1
for item in data:
ws.cell(row=current_row, column=1, value=item['Tiêu đề bài viết']).font = Font(name='Times New Roman')
ws.cell(row=current_row, column=2, value=item['Từ khóa chính của bài viết']).font = Font(name='Times New Roman')
ws.cell(row=current_row, column=3, value=item['Đường dẫn bài viết']).font = Font(name='Times New Roman')
ws.cell(row=current_row, column=4, value=item['Ngày đăng/Ngày dự kiến']).font = Font(name='Times New Roman')
ws.cell(row=current_row, column=5, value='Nguyễn Ngọc Long').font = Font(name='Times New Roman')
ws.cell(row=current_row, column=6, value=today_str).font = Font(name='Times New Roman')
current_row += 1
Save the workbook with the specified filename
filename = f"Báo cáo {datetime.today().strftime('%d.%m.%Y')} (Long).xlsx"
wb.save(filename)
print(f"Excel file '{filename}' has been created successfully.")
To add the two new columns "Website" and "Đường dẫn chỉnh sửa bài viết" to your Excel output, we need to extract the necessary information from the HTML content you've parsed. Here's how you can modify your existing code to achieve this:
1. Extract the Post ID and Website:
Post ID: Extract the post ID from the id attribute of each post row (<tr>) which is in the format post-<post_id>.
Website: Parse the view_link to get the base URL (scheme and netloc) which represents the website.
2. Construct the Edit Link:
Using the extracted website and post_id, construct the edit link in the format: https://<website>/wp-admin/post.php?post=<post_id>&action=edit.
3. Update the Data Dictionary:
Include the new fields Website and Đường dẫn chỉnh sửa bài viết in your data list.
4. Modify the Excel Output:
Update the headers list to include the new columns.
Adjust the column_widths to accommodate the new columns.
Modify the loop that writes data to the Excel file to include the new fields.
Here's the updated code with the necessary changes:
python
import re
from bs4 import BeautifulSoup
from openpyxl import Workbook
from datetime import datetime
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.utils import get_column_letter
from urllib.parse import urlparse
# Read the content from the .txt file
with open('combined_source_code.txt', 'r', encoding='utf-8') as file:
content = file.read()
# Parse the HTML content
soup = BeautifulSoup(content, 'html.parser')
# Find all posts
posts = soup.find_all('tr', id=re.compile('^post-'))
# Prepare data extraction
data = []
for post in posts:
# Extract Post Name (Tiêu đề bài viết)
post_title_div = post.find('div', class_='post_title')
if post_title_div:
post_title = post_title_div.text.strip()
else:
continue # Skip if no title found
# Extract Keyword (Từ khóa chính của bài viết)
input_focus_keyword = post.find('input', {'data-field': 'focus_keyword'})
if input_focus_keyword:
keyword = input_focus_keyword.get('value', '').strip()
else:
keyword = ''
# Extract Link (Đường dẫn bài viết)
view_link = None
row_actions = post.find('div', class_='row-actions')
if row_actions:
view_action = row_actions.find('span', class_='view')
if view_action and view_action.find('a'):
view_link = view_action.find('a')['href']
# Extract Date (Ngày đăng/Ngày dự kiến)
date_td = post.find('td', class_='date column-date')
if date_td:
date_text = date_td.get_text(separator=' ').strip()
# Extract date using regex
match = re.search(r'(\d{2}/\d{2}/\d{4} lúc \d{1,2}:\d{2} (chiều|sáng))', date_text)
if match:
date_published = match.group(1)
else:
date_published = ''
else:
date_published = ''
# Extract Post ID from the 'tr' id attribute
post_id_attr = post.get('id', '')
post_id_match = re.match(r'post-(\d+)', post_id_attr)
if post_id_match:
post_id = post_id_match.group(1)
else:
post_id = ''
# Extract Website from 'view_link'
if view_link:
parsed_url = urlparse(view_link)
website = f"{parsed_url.scheme}://{parsed_url.netloc}"
else:
website = ''
# Construct 'Đường dẫn chỉnh sửa bài viết' (Edit link)
if website and post_id:
edit_link = f"{website}/wp-admin/post.php?post={post_id}&action=edit"
else:
edit_link = ''
# Append to data list
data.append({
'Tiêu đề bài viết': post_title,
'Từ khóa chính của bài viết': keyword,
'Website': website,
'Đường dẫn bài viết': view_link,
'Đường dẫn chỉnh sửa bài viết': edit_link,
'Ngày đăng/Ngày dự kiến': date_published
})
# Create an Excel workbook and select the active worksheet
wb = Workbook()
ws = wb.active
# Set the font for the entire worksheet to Times New Roman
for row in ws.iter_rows():
for cell in row:
cell.font = Font(name='Times New Roman')
# Merge cells A1 to H1 and format
ws.merge_cells('A1:H1')
today_str = datetime.today().strftime('%d/%m/%Y')
ws['A1'] = f"Báo cáo An Nhiên Group Hòa Bình ngày {today_str} (Long)"
ws['A1'].font = Font(name='Times New Roman', size=20, bold=True)
ws['A1'].alignment = Alignment(horizontal='center')
# Set cell A3 with specified text
ws['A3'] = f"1. Bài viết đã đăng (Đăng bài viết ngày {today_str})"
ws['A3'].font = Font(name='Times New Roman', size=15, bold=True)
# Set headers starting from row 4
headers = [
'Tiêu đề bài viết',
'Từ khóa chính của bài viết',
'Website',
'Đường dẫn bài viết',
'Đường dẫn chỉnh sửa bài viết',
'Ngày đăng/Ngày dự kiến',
'Người đăng bài',
'Ngày viết'
]
header_row = 4
for col_num, header in enumerate(headers, 1):
cell = ws.cell(row=header_row, column=col_num, value=header)
cell.font = Font(name='Times New Roman', bold=True)
cell.fill = PatternFill(start_color='FFE4D5', end_color='FFE4D5', fill_type='solid')
# Adjust column widths
column_widths = [40, 30, 30, 50, 50, 25, 20, 15]
for i, width in enumerate(column_widths, 1):
ws.column_dimensions[get_column_letter(i)].width = width
# Add extracted data to the worksheet
current_row = header_row + 1
for item in data:
ws.cell(row=current_row, column=1, value=item['Tiêu đề bài viết']).font = Font(name='Times New Roman')
ws.cell(row=current_row, column=2, value=item['Từ khóa chính của bài viết']).font = Font(name='Times New Roman')
ws.cell(row=current_row, column=3, value=item['Website']).font = Font(name='Times New Roman')
ws.cell(row=current_row, column=4, value=item['Đường dẫn bài viết']).font = Font(name='Times New Roman')
ws.cell(row=current_row, column=5, value=item['Đường dẫn chỉnh sửa bài viết']).font = Font(name='Times New Roman')
ws.cell(row=current_row, column=6, value=item['Ngày đăng/Ngày dự kiến']).font = Font(name='Times New Roman')
ws.cell(row=current_row, column=7, value='Nguyễn Ngọc Long').font = Font(name='Times New Roman')
ws.cell(row=current_row, column=8, value=today_str).font = Font(name='Times New Roman')
current_row += 1
# Save the workbook with the specified filename
filename = f"Báo cáo {datetime.today().strftime('%d.%m.%Y')} (Long).xlsx"
wb.save(filename)
print(f"Excel file '{filename}' has been created successfully.")
Explanation of Changes:
Import urlparse:
python
from urllib.parse import urlparse
Extract Post ID and Website:
python
# Extract Post ID from the 'tr' id attribute
post_id_attr = post.get('id', '')
post_id_match = re.match(r'post-(\d+)', post_id_attr)
if post_id_match:
post_id = post_id_match.group(1)
else:
post_id = ''
# Extract Website from 'view_link'
if view_link:
parsed_url = urlparse(view_link)
website = f"{parsed_url.scheme}://{parsed_url.netloc}"
else:
website = ''
Note: This code assumes that the view_link contains the full URL with the domain name from which we can extract the website. If view_link is None or doesn't contain the domain, the website field will be empty.
This modification should provide you with the desired Excel output, including the two new columns with the WordPress website name and the edit link for each post.