国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python 獲取頁面表格數據存放到csv中的方法

2020-02-16 00:20:50
字體:
來源:轉載
供稿:網友

獲取單獨一個table,代碼如下:

#!/usr/bin/env python3# _*_ coding=utf-8 _*_import csvfrom urllib.request import urlopenfrom bs4 import BeautifulSoupfrom urllib.request import HTTPErrortry:  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 csvfrom urllib.request import urlopenfrom bs4 import BeautifulSoupfrom urllib.request import HTTPErrortry:  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 = 1for 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中的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 桦川县| 通榆县| 嘉峪关市| 阿克陶县| 壤塘县| 邹城市| 安图县| 静乐县| 宁城县| 涟源市| 崇阳县| 肥城市| 临桂县| 资阳市| 山东省| 蛟河市| 新乐市| 水富县| 封丘县| 龙胜| 漳平市| 潞西市| 环江| 台北县| 治县。| 遵义县| 竹北市| 台南市| 昌黎县| 连山| 红河县| 永兴县| 惠东县| 政和县| 镇雄县| 乌海市| 鄯善县| 金秀| 南溪县| 南川市| 高陵县|