我如何将此信息放在列中?

问题描述 投票:0回答:1

我的代码正在运行。但是我需要列中的信息。有人可以帮助我吗?我先谢谢你。

from bs4 import BeautifulSoup
import csv


#Request webpage content
result = requests.get('https://www.solar.com/learn/solar-panel-cost/')

#Save content in var
src = result.content

#soupactivate
soup = BeautifulSoup(src,'lxml')


#Open CSV
file = open('priceperwatt','w')
writer = csv.writer(file)

for tr in soup.findAll('tr'):
    rowtext = tr.get_text()
    writer.writerow([rowtext])

file.close()
python beautifulsoup python-3.7
1个回答
0
投票

所以我对您的代码做了一些改进。主要问题是要抓取的数据不适合数组,因为前几行包含的元素数不相同。但是一旦进入['状态','每瓦市场价格','Solar.com每瓦价格'],您就可以将其用作列标题。

from bs4 import BeautifulSoup
import requests
import csv


#Request webpage content
result = requests.get('https://www.solar.com/learn/solar-panel-cost/')

#Save content in var
src = result.content

#soupactivate
soup = BeautifulSoup(src,'lxml')


#Open CSV
with open('priceperwatt','w', newline='') as file:
    writer = csv.writer(file)

    for tr in soup.findAll('tr'):
        rowtext = tr.get_text()
        writer.writerow([rowtext])

with open('priceperwatt','r', newline='') as file:
    reader = csv.reader(file)
    for row in reader:
        row = ''.join(row).strip('\n').split('\n')
        print(row)

输出:

['Solar Price Per Watt', 'Solar Price Per Kilowatt Hour']
['GROSS system cost / Total system wattage', 'NET system cost / Total lifetime system production']
['Useful for comparing solar quotes against one another', 'Useful for comparing solar versus utility bill']
['Pertains to the POWER of a system', 'Pertains to the PRODUCTION of a system']
['Typically $3.00-4.00/watt', 'Typically $0.06-0.08/kWh']
['State', 'Market Price Per Watt', 'Solar.com Price Per Watt']
['Arizona', '$3.61/W', '$3.39/W']
['California', '$4.31/W', '$3.76/W']
['Connecticut', '$3.65/W', '$3.68/W']
['Florida', '$3.45/W', '$2.82/W']
['Massachusetts', '$4.18/W', '$3.92/W']
['Maryland', '$3.93/W', '$3.64/W']
['Minnesota', '$4.61/W', '$3.66/W']
['New Hampshire', '$3.72/W', '$3.37/W']
['New Mexico', '$4.82/W', '$3.56/W']
['Oregon', '$3.79/W', '$3.68/W']
['Texas', '$3.83/W', '$3.17/W']
['Wisconsin', '$3.29/W', '$3.83/W']
© www.soinside.com 2019 - 2024. All rights reserved.