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

作者:云中不知人 时间:2021-01-28 02:13:48 

获取单独一个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

来源:https://blog.csdn.net/u011085172/article/details/73810708

标签:python,csv
0
投稿

猜你喜欢

  • 栈和队列数据结构的基本概念及其相关的Python实现

    2022-03-14 23:18:28
  • Go语言ORM框架构造查询条件示例详解

    2024-05-05 09:29:30
  • python函数map()和partial()的知识点总结

    2023-10-04 14:58:11
  • mysql 5.7.23 安装配置方法图文教程

    2024-01-14 02:58:36
  • 详解Mysql主从同步配置实战

    2024-01-14 16:36:13
  • 详解使用vue-router进行页面切换时滚动条位置与滚动监听事件

    2024-05-08 09:34:39
  • Django压缩静态文件的实现方法详析

    2023-06-15 05:31:33
  • Mysql实现定时清空一张表的旧数据并保留几条数据(推荐)

    2024-01-17 06:38:11
  • Python进阶学习之特殊方法实例详析

    2022-03-03 22:15:04
  • 基于python实现聊天室程序

    2022-09-26 07:50:33
  • Python模块结构与布局操作方法实例分析

    2021-11-26 10:49:31
  • 基于Python实现主机远程控制

    2023-11-24 17:27:31
  • python自动化测试之如何解析excel文件

    2022-08-28 08:24:36
  • 使用Python项目生成所有依赖包的清单方式

    2022-02-18 19:14:49
  • 解决python中文乱码问题方法总结

    2022-01-30 18:47:56
  • Python实现自动添加脚本头信息的示例代码

    2022-07-02 18:12:42
  • Python通过for循环理解迭代器和生成器实例详解

    2022-08-23 14:34:59
  • Python3创建Django项目的几种方法(3种)

    2021-12-28 00:41:44
  • Python高阶函数与装饰器函数的深入讲解

    2023-10-04 12:42:41
  • ASP新闻分页,将一篇过长的文章分页,生成静态页面

    2011-04-10 11:14:00
  • asp之家 网络编程 m.aspxhome.com