我是网络抓取新手,我正在尝试从该网站抓取 2022 年福布斯排行榜 - https://en.wikipedia.org/wiki/List_of_largest_companies_in_India, 但排名列和福布斯排名列都有 colspan - 2 所以表头的数量现在是 - 9 但这些表的信息现在是 - 11 所以当我尝试将信息插入到相应的表头时,我收到错误(无法设置具有不匹配列的行)。
那么如何设置排名和福布斯排名的 colspan 呢?
这是我的代码:
from bs4 import BeautifulSoup
import requests
url = 'https://en.wikipedia.org/wiki/List_of_largest_companies_in_India'
page = requests.get(url)
soup = BeautifulSoup(page.text,'html')
soup.find('table')
table = soup.find('table')
titles = table.find_all('th')
Table_Title = [title.text.strip() for title in titles]
import pandas as pd
df = pd.DataFrame(columns = Table_Title)
df
column_data = table.find_all('tr')
column_data
for row in column_data[1:]:
row_data = row.find_all('td')
individual_row_data = [data.text.strip() for data in row_data]
length = len(df)
df.loc[length] = individual_row_data
print(individual_row_data)
由于您想要创建一个
dataframe
并且已经包含了 pandas
,最优雅的解决方案是使用 [pandas.read_html()
][1] 来抓取表数据:
pd.read_html('https://en.wikipedia.org/wiki/List_of_largest_companies_in_India')[0]
排名 | 排名1 | 福布斯2000强排名 | 福布斯2000强排名1 | 姓名 | 总部 | 收入(十亿美元) | 利润(十亿美元) | 资产(十亿美元) | 价值(十亿美元) | 行业 | |
---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | (0) | 54 | (+1) | 信实工业 | 孟买 | 86.85 | 7.81 | 192.59 | 228.63 | 企业集团 |
... | |||||||||||
50 | 51 | (0) | 1759 | (+208) | 大卖场 | 孟买 | 4 | 0.20 | 1.93 | 34.12 | 零售 |
51 | 52 | (0) | 1759 | (+208) | 阿迪亚·阿南达·巴万 | 钦奈 | 4 | 0.20 | 1.93 | 34.12 | 零售 |
或者,您可以使用
beautifulsoup
选择并将标题乘以 colspan
的值:
Table_Title = []
for title in table.find_all('th'):
if title.get('colspan'):
Table_Title.extend([title.get_text(strip=True)]*int(title.get('colspan')))
else:
Table_Titlepandas.pydata.org/docs/reference/api/pandas.read_html.html