python第六章课后习题(2)

2.读取第一题中具有单一表格的html文件,将其中表格的所有数据用bs4提取出来,并保存为同名的csv文件。

提示:

1) 对于本地文件,可以用文件的方式读取其中的内容,并将该内容作为bs4的参数。

2) 解析器可以使用lxml,它是一个单独的库,如果不存在,请用pip install lxml进行安装。

卡了一上午,难受

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'
    
    path1=Path(in_file)
    tablel=path1.read_text()
    soup=BS(tablel,"lxml")
    table=soup.find_all('tr')
    with open(out_file,'w',newline='')as f1:
        for row in table:
            cols=[col.text for col in row.find_all('td')]
            f_csv = csv.writer(f1)
            f_csv.writerow(cols)

猜你喜欢

转载自blog.csdn.net/qq_53029299/article/details/114866710