|
| 1 | +from bs4 import BeautifulSoup |
| 2 | + |
| 3 | +def remove_class_prefix_from_sidebar(html_file): |
| 4 | + with open(html_file, 'r', encoding='utf-8') as f: |
| 5 | + content = f.read() |
| 6 | + |
| 7 | + soup = BeautifulSoup(content, 'html.parser') |
| 8 | + |
| 9 | + # 找 class="sphinxsidebarwrapper" 侧边栏 |
| 10 | + sidebar = soup.find('div', class_='sphinxsidebarwrapper') |
| 11 | + |
| 12 | + if sidebar: |
| 13 | + # 找 class="pre" 的 span 标签 |
| 14 | + for span in sidebar.find_all('span', class_='pre'): |
| 15 | + text = span.get_text() |
| 16 | + # 删除 '.' 之前的内容 |
| 17 | + if '.' in text: |
| 18 | + method_name = text.split('.')[1] |
| 19 | + # 更新 <a> 标签,保证跳转有效 |
| 20 | + for a_tag in sidebar.find_all('a', class_='reference internal'): |
| 21 | + if text in a_tag.get_text(): |
| 22 | + href = a_tag['href'] |
| 23 | + new_href = href.replace(text, method_name) |
| 24 | + a_tag['href'] = new_href |
| 25 | + print(f"Updated href: {href} -> {new_href}") |
| 26 | + new_span = soup.new_tag("span", **{"class": "pre"}) |
| 27 | + new_span.string = method_name |
| 28 | + span.replace_with(new_span) |
| 29 | + |
| 30 | + try: |
| 31 | + with open(html_file, 'w', encoding='utf-8') as f: |
| 32 | + f.write(str(soup)) |
| 33 | + print(f"Successfully wrote changes back to {html_file}") |
| 34 | + except Exception as e: |
| 35 | + print(f"Error writing to file: {e}") |
| 36 | + else: |
| 37 | + print("No sidebar found in the HTML.") |
| 38 | + |
| 39 | +input_html = './build/html/src.html' |
| 40 | +remove_class_prefix_from_sidebar(input_html) |
0 commit comments