modify the script to output the script into .csv form, write the column header name in english and add 2 new columns named wp_site_name that contains the wordpress site name and wp_edit_link that contains the edit link (example: https://www.chungkhoan6688.com/wp-admin/post.php?post=1478&action=edit).
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.")
Certainly! I've modified the script according to your requirements:
The output is now in CSV format.
Column headers are in English.
Added two new columns: WordPress Site Name (wp_site_name) and Edit Link (wp_edit_link).
Here's the updated script:
python
import re
from bs4 import BeautifulSoup
from urllib.parse import urlparse
import csv
from datetime import datetime
# 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 Title
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 Main Keyword
input_focus_keyword = post.find('input', {'data-field': 'focus_keyword'})
if input_focus_keyword:
keyword = input_focus_keyword.get('value', '').strip()
else:
keyword = ''
# Extract Post URL (view_link)
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']
else:
view_link = ''
# Extract Publish Date/Scheduled Date
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 post['id']
post_id = post.get('id', '')
if post_id:
post_id = post_id.replace('post-', '').strip()
else:
post_id = ''
# Extract wp_site_name from view_link
if view_link:
parsed_url = urlparse(view_link)
wp_site_name = parsed_url.netloc
else:
wp_site_name = ''
# Construct wp_edit_link
if wp_site_name and post_id:
wp_edit_link = f"https://{wp_site_name}/wp-admin/post.php?post={post_id}&action=edit"
else:
wp_edit_link = ''
# Append to data list
data.append({
'Post Title': post_title,
'Main Keyword': keyword,
'Post URL': view_link,
'Publish Date/Scheduled Date': date_published,
'Author': 'Nguyễn Ngọc Long',
'Date Written': datetime.today().strftime('%d/%m/%Y'),
'WordPress Site Name': wp_site_name,
'Edit Link': wp_edit_link
})
# Define headers
headers = [
'Post Title',
'Main Keyword',
'Post URL',
'Publish Date/Scheduled Date',
'Author',
'Date Written',
'WordPress Site Name',
'Edit Link'
]
# Write data to CSV file
filename = f"Report {datetime.today().strftime('%d.%m.%Y')} (Long).csv"
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=headers)
# Write the headers
writer.writeheader()
# Write data rows
for item in data:
writer.writerow(item)
print(f"CSV file '{filename}' has been created successfully.")
Explanation of Modifications:
CSV Output: Replaced the Excel workbook creation with writing to a CSV file using the csv module.
English Headers: Changed the header names to English equivalents.
Added Columns:
WordPress Site Name (wp_site_name): Extracted from the view_link using urlparse.
Edit Link (wp_edit_link): Constructed using the wp_site_name and post_id.
Note on Data Extraction:
Post ID (post_id): Extracted from the id attribute of the <tr> element.
WordPress Site Name (wp_site_name): Extracted from the view_link URL.
Edit Link (wp_edit_link): Constructed as https://{wp_site_name}/wp-admin/post.php?post={post_id}&action=edit.
Output:
The script creates a CSV file named something like Report 27.10.2023 (Long).csv, containing the extracted data with the specified columns.
Usage:
Make sure to have the combined_source_code.txt file in the same directory as the script. Then run the script using:
bash
python script_name.py
Replace script_name.py with the actual name of your Python script file.
Dependencies:
BeautifulSoup (bs4 library): For parsing HTML content.
re module: For regular expressions.
urllib.parse: For URL parsing.
csv module: For writing CSV files.
Ensure all necessary libraries are installed before running the script.