python 獲取頁面表格數(shù)據(jù)存放到csv中的方法
更新時間:2018年12月26日 15:16:02 作者:云中不知人
今天小編就為大家分享一篇python 獲取頁面表格數(shù)據(jù)存放到csv中的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
獲取單獨一個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 獲取頁面表格數(shù)據(jù)存放到csv中的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- python 刪除excel表格重復(fù)行,數(shù)據(jù)預(yù)處理操作
- Python3讀取和寫入excel表格數(shù)據(jù)的示例代碼
- 基于Python快速處理PDF表格數(shù)據(jù)
- Python基于pandas爬取網(wǎng)頁表格數(shù)據(jù)
- 基于python實現(xiàn)把json數(shù)據(jù)轉(zhuǎn)換成Excel表格
- 使用 Python 讀取電子表格中的數(shù)據(jù)實例詳解
- python讀取word 中指定位置的表格及表格數(shù)據(jù)
- python 中Arduino串口傳輸數(shù)據(jù)到電腦并保存至excel表格
- Python 用三行代碼提取PDF表格數(shù)據(jù)
- Python獲取數(shù)據(jù)庫數(shù)據(jù)并保存在excel表格中的方法
- python3 讀取Excel表格中的數(shù)據(jù)
- 利用python做表格數(shù)據(jù)處理
相關(guān)文章
Windows環(huán)境下python環(huán)境安裝使用圖文教程
這篇文章主要為大家詳細(xì)介紹了Windows環(huán)境下python安裝使用圖文教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03
Python獲取命令實時輸出-原樣彩色輸出并返回輸出結(jié)果的示例
今天小編就為大家分享一篇Python獲取命令實時輸出-原樣彩色輸出并返回輸出結(jié)果的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
在Django的form中使用CSS進(jìn)行設(shè)計的方法
這篇文章主要介紹了在Django的form中使用CSS進(jìn)行設(shè)計的方法,Django是Python重多人氣開發(fā)框架中最為著名的一個,需要的朋友可以參考下2015-07-07
在Python的Django框架的視圖中使用Session的方法
這篇文章主要介紹了在Python的Django框架的視圖中使用Session的方法,包括相關(guān)的設(shè)置測試Cookies的方法,需要的朋友可以參考下2015-07-07

