博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python提取网页表格并保存为csv
阅读量:4561 次
发布时间:2019-06-08

本文共 2492 字,大约阅读时间需要 8 分钟。

0.

 

1.参考

表格标签

表格 描述
定义表格
定义表格标题。
定义表格的表头。
定义表格的行。
定义表格单元。
定义表格的页眉。
定义表格的主体。
定义表格的页脚。
定义用于表格列的属性。
定义表格列的组。

 

 

表格元素定位

参看网页源代码并没有 thead 和 tbody。。。

  
  
    
    
    
    
    
    
    
    
    
    
    
  
  
    
List of text editors
Name Creator First public release Latest stable version Latest Release Date Programming language Cost (US$) Software license Open source Cli available Minimum installed size

2.提取表格数据

表格标题可能出现超链接,导致标题被拆分,

也可能不带表格标题。。

Text editor support for remote file editing over   network protocols 

 

表格内容换行

   Plan 9    and   Inferno 

 

tag 规律

table        
thead tr1 th th th th
tbody tr2 td/th td
tbody tr3 td/th
tbody tr3 td/th

 

2.1提取所有表格标题列表

filenames = []for index, table in enumerate(response.xpath('//table')):    caption = table.xpath('string(./caption)').extract_first()    #提取caption tag里面的所有text,包括子节点内的和文本子节点,这样也行 caption = ''.join(table.xpath('./caption//text()').extract())    filename = str(index+1)+'_'+caption if caption else str(index+1)  #xpath 要用到 table 计数,从[1]开始    filenames.append(re.sub(r'[^\w\s()]','',filename))    #移除特殊符号In [233]: filenamesOut[233]:[u'1_List of text editors', u'2_Text editor support for various operating systems', u'3_Available languages for the UI', u'4_Text editor support for common document interfaces', u'5_Text editor support for basic editing features', u'6_Text editor support for programming features (see source code editor)', u'7_Text editor support for other programming features', '8', u'9_Text editor support for key bindings', u'10_Text editor support for remote file editing over network protocols', u'11_Text editor support for some of the most common character encodings', u'12_Right to left (RTL)  bidirectional (bidi) support', u'13_Support for newline characters in line endings']

 

2.2每个表格分别写入csv文件

for index, filename in enumerate(filenames):    print filename    with open('%s.csv'%filename,'wb') as fp:        writer = csv.writer(fp)        for tr in response.xpath('//table[%s]/tr'%(index+1)):            writer.writerow([i.xpath('string(.)').extract_first().replace(u'\xa0', u' ').strip().encode('utf-8','replace') for i in tr.xpath('./*')])  #xpath组合,限定 tag 范围,tr.xpath('./th | ./td')

 

代码处理 .replace(u'\xa0', u' ')

使用 'w' 写csv文件,会出现如下问题,使用'wb' 即可解决问题

所有表格写入同一excel文件的不同工作表 sheet,需要使用xlwt

 

转载于:https://www.cnblogs.com/my8100/p/save_html_table_to_csv.html

你可能感兴趣的文章
learnByWork
查看>>
Unity3D热更新之LuaFramework篇[04]--自定义UI监听方法
查看>>
lua 函数
查看>>
Git的基本命令
查看>>
四平方和
查看>>
第十八周 12.27-1.2
查看>>
Linux平台下java程序员的基本功(七)
查看>>
C# IP地址字符串和数值转换
查看>>
TCHAR和CHAR类型的互转
查看>>
常用界面布局
查看>>
C语言—— for 循环
查看>>
IBM lotus9.0测试版即将公测
查看>>
xml常用方法
查看>>
Cube Stacking(并差集深度+结点个数)
查看>>
AndroidStudio3更改包名失败
查看>>
jq 删除数组中的元素
查看>>
添加按键事件处理及事件处理的参数传递
查看>>
js URL中文传参乱码
查看>>
Leetcode 367. Valid Perfect Square
查看>>
UVALive 3635 Pie(二分法)
查看>>