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中open()函数指定文件打开方式的用法

文件打开方式 当我们用open()函数去打开文件的时候,有好几种打开的模式。 'r'->只读 'w'->只写,文件已存在则清空,不存在则创建。 'a'->追加,写到文件...

对python中url参数编码与解码的实例详解

一、简介 在python中url,对于中文等非ascii码字符,需要进行参数的编码与解码。 二、关键代码 1、url编码 对字符串编码用urllib.parse包下的quote(stri...

OpenCV 轮廓检测的实现方法

OpenCV 轮廓检测的实现方法

轮廓概述 轮廓可以简单认为成将连续的点(连着边界)连在一起的曲线,具有相同的颜色或者灰度。轮廓在形状分析和物体的检测和识别中很有用。  为了更加准确,要使用二值化图像...

解决python 读取 log日志的编码问题

解决python 读取 log日志的编码问题

1.我要读取log日志的”执行成功”的个数,log日志编码格式为GBK 2.显示报错,大致意思是说utf-8的代码不能解析log日志 3.后来想想把log日志用GBK编码读出来,写到...

matplotlib实现热成像图colorbar和极坐标图的方法

matplotlib实现热成像图colorbar和极坐标图的方法

热成像图 %matplotlib inline from matplotlib import pyplot as plt import numpy as np def f(x,...