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

yipeiwu_com5年前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设计】。

相关文章

python SSH模块登录,远程机执行shell命令实例解析

用python SSH模块登录,并在远程机执行shell命令 (在CentOS 7 环境试验成功, Redhat 系列应该是兼容的。) 先安装必须的模块 # yum install...

python将数组n等分的实例

废话不多说,直接上代码! import math lists = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 16, 7, 8...

Python读取和处理文件后缀为.sqlite的数据文件(实例讲解)

Python读取和处理文件后缀为.sqlite的数据文件(实例讲解)

最近在弄一个项目分析的时候,看到有一个后缀为”.sqlite”的数据文件,由于以前没怎么接触过,就想着怎么用python来打开并进行数据分析与处理,于是稍微研究了一下。 SQLite是一...

Python读取网页内容的方法

本文实例讲述了Python读取网页内容的方法。分享给大家供大家参考。具体如下: import urllib2 #encoding = utf-8 class Crawler: d...

python编写朴素贝叶斯用于文本分类

python编写朴素贝叶斯用于文本分类

朴素贝叶斯估计 朴素贝叶斯是基于贝叶斯定理与特征条件独立分布假设的分类方法。首先根据特征条件独立的假设学习输入/输出的联合概率分布,然后基于此模型,对给定的输入x,利用贝叶斯定理求出后验...