python 获取页面表格数据存放到csv中的方法

yipeiwu_com6年前Python基础

获取单独一个table,代码如下:

#!/usr/bin/env python3
# _*_ coding=utf-8 _*_
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib.request import HTTPError
try:
  html = urlopen("http://en.wikipedia.org/wiki/Comparison_of_text_editors")
except HTTPError as e:
  print("not found")
bsObj = BeautifulSoup(html,"html.parser")
table = bsObj.findAll("table",{"class":"wikitable"})[0]
if table is None:
  print("no table");
  exit(1)
rows = table.findAll("tr")
csvFile = open("editors.csv",'wt',newline='',encoding='utf-8')
writer = csv.writer(csvFile)
try:
  for row in rows:
    csvRow = []
    for cell in row.findAll(['td','th']):
      csvRow.append(cell.get_text())
    writer.writerow(csvRow)
finally:
  csvFile.close()

获取所有table,代码如下:

#!/usr/bin/env python3
# _*_ coding=utf-8 _*_
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib.request import HTTPError
try:
  html = urlopen("http://en.wikipedia.org/wiki/Comparison_of_text_editors")
except HTTPError as e:
  print("not found")
bsObj = BeautifulSoup(html,"html.parser")
tables = bsObj.findAll("table",{"class":"wikitable"})
if tables is None:
  print("no table");
  exit(1)
i = 1
for table in tables:
  fileName = "table%s.csv" % i
  rows = table.findAll("tr")
  csvFile = open(fileName,'wt',newline='',encoding='utf-8')
  writer = csv.writer(csvFile)
  try:
    for row in rows:
      csvRow = []
      for cell in row.findAll(['td','th']):
        csvRow.append(cell.get_text())
      writer.writerow(csvRow)
  finally:
    csvFile.close()
  i += 1

以上这篇python 获取页面表格数据存放到csv中的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Django2.1.3 中间件使用详解

Django2.1.3 中间件使用详解

环境 Win10 Python3.6.6 Django2.1.3 中间件作用 中间件用于全局修改Django的输入或输出。 中间件常见用途 缓存 会话认证...

对python中的*args与**kwgs的含义与作用详解

在定义函数的时候参数通常会使用 *args与**kwgs,形参与实参的区别不再赘述,我们来解释一下这两个的作用。 *args是非关键字参数,用于元组,**kw是关键字参数 例如下面的代...

python实现按行分割文件

本文实例为大家分享了python实现按行分割文件的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python #--*-- coding:utf-8 --*--...

Python实现的建造者模式示例

本文实例讲述了Python实现的建造者模式。分享给大家供大家参考,具体如下: #!/usr/bin/python # -*- coding:utf-8 -*- #建造者基类 clas...

django实现web接口 python3模拟Post请求方式

django实现web接口 python3模拟Post请求方式

作为抛砖引玉,用python3实现百度云语音解析,首先需要模拟Post请求把音频压缩文件丢给百度解析。 但是遇到一个问题客户端怎麽丢数据都是返回错误,后来在本地用django搭建了一个接...