【问题标题】:Don't understand this "IndexError: list index out of range"不明白这个“IndexError: list index out of range”
【发布时间】:2019-06-11 21:59:09
【问题描述】:

代码未正确解析表格,我找不到找不到“”的表格数据的确切原因。有人可以帮忙吗?

from bs4 import BeautifulSoup
import requests
import pandas as pd 

url = "https://webapps1.cityofchicago.org/activeecWeb/"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, "html.parser")


table = soup.find_all('table')[1]
rows = table.find_all('tr')[1:]

data = {
    'LicenseType' : [],
    'CompanyName' : [],
    'Address' : [],
    'Phone' : [],
    'Expiration' : []
}

for row in rows:
    cols = row.find_all('td')
    data['LicenseType'].append( cols[0].get_text() )
    data['CompanyName'].append( cols[1].get_text() )
    data['Address'].append( cols[2].get_text() )  
    data['Phone'].append( cols[3].get_text() )
    data['Expiration'].append( cols[4].get_text() )

electricians = pd.DataFrame( data )
electricians.to_csv("ChicagoElectriciansData.csv")

【问题讨论】:

  • 你能用这个完整地发布错误消息吗?
  • 请在您的问题中包含完整的错误回溯,因为这可以帮助确定问题发生在哪里
  • 你也可以通过使用 pandas read_html() 而不是 bs4 来节省一些工作
  • ""中没有表格数据,我猜这就是你找不到的原因。另一方面,我看不出解析有任何问题。你能详细说明一下吗?
  • 询问错误时,您应该发布错误提供给您的所有信息,特别是确定错误发生的位置。但是我猜它发生在table = soup.find_all('table')[1],这是我看到的唯一列表索引。如果为 true,则意味着 find_all 生成了一个空列表或单个元素列表。

标签: python html web-scraping beautifulsoup


【解决方案1】:

您遇到的错误是因为该表的最后一个tr。您可以使用 try/except 子句忽略该错误。但是使用这个.find_all("tr")[1:-1] 也可以解决我在这里所做的问题:

from bs4 import BeautifulSoup
import requests
import pandas as pd 

url = "https://webapps1.cityofchicago.org/activeecWeb/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")

datalist = []

for row in soup.find('table',class_="gridStyle-table").find_all("tr")[1:-1]:
    d = {}
    d['LicenseType'] = row.find_all('td')[0].get_text(strip=True)
    d['CompanyName'] = row.find_all('td')[1].get_text(strip=True)
    d['Address'] = row.find_all('td')[2].get_text(strip=True) 
    d['Phone'] = row.find_all('td')[3].get_text(strip=True)
    d['Expiration'] = row.find_all('td')[4].get_text(strip=True)
    datalist.append(d)

electricians = pd.DataFrame(datalist)
electricians.to_csv("ChicagoElectriciansData.csv")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 2015-02-11
    • 1970-01-01
    • 2020-10-27
    • 2018-02-08
    • 2014-10-20
    相关资源
    最近更新 更多