簡體   English   中英

使用 BeautifulSoup 從 python 導出到.csv

[英]Exporting to .csv from python with BeautifulSoup

我對此很陌生,似乎無法正確導出。

# select document
with open('scrape1.html') as html_file:
    soup = BeautifulSoup(html_file, 'lxml')

# create/name csv
with open('speechengine_report.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(['computer', 'usagedata']) 

# tell bs4 to only look at x tags with a class of y
for licensedata in soup.find_all('div', class_='licensedata'):

    # scrape pc id
    computer = licensedata.p.b.text
    print(computer)

    # scrape usage stats for each id
    for usagedata in licensedata.find_all('td'):

        # minutes = usagedata.table.tbody
        print(usagedata.text)

    # blank line
    print()

    # writer.writerow([computer, usagedata])

    
csv_file.close()

您想要將數據寫入 csv 文件的代碼的 Rest 應該在with塊內。 此外,您不需要 csv_file.close() ,因為它會為您處理。 試試下面的代碼。 在 python 中讀取文件處理

with open('scrape1.html') as html_file:
    soup = BeautifulSoup(html_file, 'lxml')

# create/name csv
with open('speechengine_report.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(['computer', 'usagedata']) 
    # tell bs4 to only look at x tags with a class of y
    for licensedata in soup.find_all('div', class_='licensedata'):

        # scrape pc id
        computer = licensedata.p.b.text
        print(computer)

        # scrape usage stats for each id
        for usagedata in licensedata.find_all('td'):

        # minutes = usagedata.table.tbody
            print(usagedata.text)

        # blank line
        print()

        # writer.writerow([computer, usagedata])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM