欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-07 08:10:41
获取单独一个table,代码如下: #!/usr/bin/env python3 # _*_ coding=utf-8 _*_ import csv fro...

获取单独一个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中的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。