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

首頁 > 編程 > Python > 正文

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

2020-01-04 13:41:46
字體:
來源:轉載
供稿:網友

獲取單獨一個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中的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 迭部县| 郯城县| 清水县| 夏津县| 汝州市| 福清市| 北川| 南陵县| 安陆市| 洱源县| 扶绥县| 上思县| 晋中市| 阿坝县| 宁城县| 营口市| 富阳市| 宝应县| 香格里拉县| 紫云| 蕉岭县| 同德县| 萨迦县| 澄迈县| 衡水市| 铁力市| 旅游| 洛南县| 沂源县| 缙云县| 莆田市| 电白县| 梅河口市| 平利县| 沙洋县| 阿克苏市| 棋牌| 孝感市| 涟源市| 冕宁县| 堆龙德庆县|