【问题标题】:TypeError: 'NoneType' object is not subscriptable python web scrapingTypeError:'NoneType' 对象不可下标 python web 抓取
【发布时间】:2019-07-12 13:56:15
【问题描述】:

我正在尝试从一个用 html 编写的网站上抓取信息。下面附上我的代码:

#Import packages
import urllib.request
from bs4 import BeautifulSoup
import pandas as pd
import csv   


#For loop to scrape details of power plants
lst=[]
for i in range(1,46624):
     pid=str(i)
     url="http://www.globalenergyobservatory.com/form.php?pid=" + pid
     page=urllib.request.urlopen(url)
     soup=BeautifulSoup(page,'html.parser')

     #Distinguish power plants to different types of primary fuel
     types=soup.find(id="Type")
     power_types=types["value"]


     #No of units of power plant
     unit=soup.find(id="Abstract_Block")
     unit_breakdown_describe=unit.get_text()

     #Name of power plant
     name=soup.find(id="Name")
     name_value=name["value"]

     #Status of power plant
     status1=soup.find(id="Status_of_Plant_enumfield_itf")
     status2=status1.find(selected="selected") 
     status=status2["value"]

     #Latitude & longitude of power plant
     lat=soup.find(id="Latitude_Start")
     latitude=lat["value"]
     long=soup.find(id="Longitude_Start")
     longitude=long["value"]

     #Capacity of power plant
     cap=soup.find(id="Design_Capacity_(MWe)_nbr") 
     capacity=cap["value"]

lst.append([name_value,status,power_types,capacity,latitude,longitude,unit_breakdown_describe])
df=pd.DataFrame(lst)    #Convert to dataframe for storage
df.columns=['Name','Status','Type_of_power_plant','Capacity','Latitude','Longitude','no_of_units'] 

#Convert to csv file
df.to_csv('power.csv',sep='\t') 

我正在尝试抓取信息并将其放入DataFrame 以转换为csv 文件。虽然我在尝试运行各个值(例如 print(capacity))时没有遇到任何错误,但当我尝试转换为 csv 文件时出现了错误。我知道在这方面有类似的主题,但我希望任何帮助都将不胜感激。

【问题讨论】:

  • 看起来您尝试绑定数据的方式存在问题。当我尝试 2 次迭代时效果很好。

标签: python html beautifulsoup export-to-csv


【解决方案1】:

我看到的唯一错误是您将数据添加到列表的行没有正确缩进 它应该在循环内,并且将正确填写 csv

lst=[]
for i in range(1,46624):

    # Your code here

    #Capacity of power plant
    cap=soup.find(id="Design_Capacity_(MWe)_nbr") 
    capacity=cap["value"]

    lst.append([name_value,status,power_types,capacity,latitude,longitude,unit_breakdown_describe])

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多