【问题标题】:In html table they show error Assertion Error: 22 columns passed, passed data had 21 columns在 html 表中,它们显示错误断言错误:通过了 22 列,传递的数据有 21 列
【发布时间】:2021-08-18 15:44:16
【问题描述】:

AssertionError: 22 列传递,传递的数据在 html 表中有 21 列显示错误

import requests
from bs4 import BeautifulSoup
import pandas as pd

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.3"
}
r = requests.get("https://www.worldometers.info/coronavirus/?utm_campaign=homeAdvegas1?")
soup = BeautifulSoup(r.content, "lxml")
table = soup.find("table", id="main_table_countries_yesterday")

header = [th.get_text(strip=True) for th in table.tr.select("th")][1:]

all_data = []
for row in table.select("tr:has(td)"):
    tds = [td.get_text(strip=True) for td in row.select("td")]
    all_data.append(tds)

df = pd.DataFrame(all_data, columns=header)
print(df)
df.to_csv("data.csv", index=False)

【问题讨论】:

标签: python html web-scraping beautifulsoup


【解决方案1】:

您的 header 有 21 列,all_data 的项目有 22 列。

只需在标题中添加一列即可。 我已添加 S.No 作为附加列名。

header.insert(0, 'S.No')

修改后,你的代码打印出来

    S.No  Country,Other  ... New Deaths/1M pop Active Cases/1M pop
0                  Asia  ...                                      
1         North America  ...                                      
2         South America  ...                                      
3                Europe  ...                                      
4                Africa  ...                                      
..   ...            ...  ...               ...                 ...
233              Total:  ...                                      
234              Total:  ...                                      
235              Total:  ...                                      
236              Total:  ...                                      
237              Total:  ...                                      

[238 rows x 22 columns]

【讨论】:

    【解决方案2】:

    尝试从标题列表中删除[1:]

    header = [th.get_text(strip=True) for th in table.tr.select("th")]
    

    这是删除标题的第一列,因此标题中只有 21 项,而数据有 22 项,因此出现错误。

    【讨论】:

    • header = [th.get_text(strip=True) for th in table.tr.select("th")] AttributeError: 'NoneType' object has no attribute 'tr'
    • 该错误与我建议的更新无关。看起来前面的行没有返回任何内容,因此您的table 变量被分配了None。我能够运行代码而没有错误,请尝试重新启动并再次运行
    猜你喜欢
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 2019-03-08
    相关资源
    最近更新 更多