在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ 求助:使用bs4從網(wǎng)頁獲取html表格并寫入cvs文件

求助:使用bs4從網(wǎng)頁獲取html表格并寫入cvs文件

想從 http://en.wikipedia.org/wiki/... 上獲取當前頁面上的表格并寫入cvs文件,但是最后得到的cvs文件,顯示只導出了網(wǎng)頁第一個表格的最后一行數(shù)據(jù),其它行的數(shù)據(jù)都沒導出來,請問這是怎么回事?

這個案例來自《python網(wǎng)絡數(shù)據(jù)采集》這本書第5章,完全是照書上的代碼打的,但是得不到書上說的結果。

import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://en.wikipedia.org/wiki/Comparison_of_text_editors")
bsObj = BeautifulSoup(html,"lxml")
table = bsObj.findAll("table", {"class":"wikitable"})[0]
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()

數(shù)據(jù)導出結果:
圖片描述

回答
編輯回答
尤禮
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://en.wikipedia.org/wiki/Comparison_of_text_editors")
bsObj = BeautifulSoup(html,"lxml")
table = bsObj.findAll("table", {"class":"wikitable"})[0]
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()
2017年5月19日 02:33