完成这段代码:import csv from pathlib import Path from bs4 import BeautifulSoup as BS def fun2(filename='test'): in_file = f'{path}/{filename}.html' out_file = f'{path}/{filename}.csv'将以下表格的所有数据用bs4提取出来,并保存为同名的csv文件:<!DOCTYPE html><html><head> <title>Test Table</title></head><body> <table border="1"> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr> <tr> <td>5</td> <td>6</td> </tr> </table></body></html>
时间: 2023-06-02 11:02:40 浏览: 161
import reimport requestsfrom bs4 import BeautifulSoupimport t
import csv
from pathlib import Path
from bs4 import BeautifulSoup as BS
path = Path.cwd()
def fun2(filename='test'):
in_file = f'{path}/{filename}.html'
out_file = f'{path}/{filename}.csv'
with open(in_file, 'r') as f:
soup = BS(f, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
with open(out_file, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for row in rows:
cols = row.find_all('td')
cols = [col.text.strip() for col in cols]
writer.writerow(cols)
阅读全文