import csv
import os
import xlwt
# import re
from urllib.request import urlopen
from bs4 import BeautifulSoup
# 先获取表格进行锁定
# 获取每一行数据,变量接收
# 写入文件,指定存放位置
def get_cvs_data(url):
"""
读取页面表格数据并下载导出为csv文件
:param url:
:return:
"""
html = urlopen(url)
bsObj = BeautifulSoup(html, "html.parser")
oTables = bsObj.find("table") # 选定第一个表格
# oTables2 =bsObj.select('.fixed-table-loading')
# 选定第一个表格
# for table in oTables:
if oTables:
# 获取表格名称
sTitleTag = 'test' # 标题只有一个
# sMatchText = re.compile(r'<[^>]+>', re.S)
# sTextRemain = sMatchText.sub('', sTitleTag)
sTitleName = sTitleTag + '.csv'
# 路劲不存在是需要新建
sDir = 'files'
if not os.path.exists(sDir):
os.mkdir(sDir)
sCSV_Path = os.path.join(sDir, sTitleName)
rows = oTables.find_all("tr") # tr为每一行的标签
with open(sCSV_Path, 'wt', newline='', encoding='utf-8') as csvFile: # 创建可写文件
writer = csv.writer(csvFile)
for row in rows: # 先按行处理
csvRow = [] # 创建列表存储每行数据
for cell in row.find_all(['td', 'th']): # 再按列处理,搜索一行中每格的内容,td或th都可以
csvRow.append(cell.get_text()) # 将每格中的数据追加到列表
writer.writerow(csvRow) # 写入一行
if __name__ == '__main__':
write_excel()
get_cvs_data('')
数据导出为csv文件
猜你喜欢
转载自blog.csdn.net/weixin_42322206/article/details/101164314
今日推荐
周排行