顺带保存URL的页面标题和链接。其中URL从url.txt
中读取。
首先通过selenium获取表格
import os
import time
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
with open("url.txt", "r") as f:
url = f.readline()
# 设置Selenium WebDriver并加载页面
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_driver_path = os.path.expanduser('~/google/chrome/chromedriver')
driver_service = Service(executable_path=chrome_driver_path)
driver = webdriver.Chrome(service=driver_service, options=chrome_options)
print("正在打开页面(等待5s):",url)
driver.get(url)
# 等待页面加载完成
time.sleep(5)
# 获取渲染后的HTML内容
html = driver.execute_script("return document.documentElement.outerHTML")
# 使用BeautifulSoup解析HTML内容并提取第一个表格
soup = BeautifulSoup(html, "html.parser")
# 获取页面标题
title = soup.title.string.strip()
pageinfo = f"[{title}]({url})\n"
print("pageinfo:",pageinfo)
tables = soup.findAll('table')
tab = tables[0]
if not tab:
print("No table found,quit")
sys.exit()
对于获取到的表单下面以三种方式来保存(更多方式请自行发挥):
1. 在Markdown文件中保存为HTML表格
保存为HTML表格可以一定程度上保留原有数据的一些格式。比如我找到的table数据中,某个单元格内有多个链接且它们之间没有空格,所以保存之前可以手动添加空格(各位看官自行斟酌)。而如果使用cell.get_text()获取文字就比较难处理这个情况。
# 链接之间添加空格
htmltable = str(tab).replace("</a>","</a> ")
# 保存到table.md
with open('table.md', 'w') as f:
f.write(pageinfo)
f.write(htmltable)
f.close()
2. 将单元格文本转为markdown表格保存
with open('table.md', 'w') as f:
f.write(pageinfo)
cnt = 0
for row in tab.find_all('tr'):
cnt += 1
cells = row.find_all('td')
f.write('|' + '|'.join(cell.get_text() for cell in cells) + '|\n')
# 把第一行作为表头
if cnt == 1:
f.write('|' + '|'.join("--" for cell in cells) + '|\n')
f.close()
3. 使用dafaframe将单元格文本转为markdown表格保存(需要安装lxml
和tabulate
)
df = pd.read_html(str(tab))[0]
# 移除多余的表头
df.rename(columns=df.iloc[0], inplace = True)
df.drop([0], inplace = True)
# 将DataFrame转换为Markdown格式
markdown_table = df.to_markdown(tablefmt="github", index=False)
with open('table.md', 'w') as f:
f.write(markdown_table)
print("markdown table:",markdown_table)
f.close()
参考资料