国产探花免费观看_亚洲丰满少妇自慰呻吟_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中的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 和林格尔县| 贺州市| 石林| 招远市| 淮安市| 长乐市| 永城市| 调兵山市| 城市| 高雄县| 从化市| 青河县| 桃江县| 涪陵区| 平果县| 家居| 阿拉尔市| 永登县| 阿勒泰市| 濮阳县| 潮州市| 安吉县| 喜德县| 宜阳县| 南宫市| 犍为县| 普宁市| 东乡族自治县| 兰溪市| 黄骅市| 赤城县| 柞水县| 西乡县| 义乌市| 巴林右旗| 香港 | 荥阳市| 汕尾市| 黑龙江省| 鄯善县| 泰宁县|