首页 > 解决方案 > 没有使用 python beautifulsoup 获取包含公司信息的嵌套表

问题描述

代码 :

from bs4 import BeautifulSoup

import requests

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'}

r = requests.get('http://indianindustriesdirectory.com/viewCompanyDetails.asp?compid=3855',headers=headers)

soup = BeautifulSoup(r.text,'lxml')

table = soup.find('table',{"width":"99%","cellpadding":"0","cellspacing":"0","border":"0"})

contact_person = table.find('b')

print(contact_person)

想要关于公司的所有信息,但我得到了桌子。

标签: python-3.xbeautifulsoup

解决方案


您所指的网址有几个看起来几乎相同的表格,所以我随机选择了其中一个(table[5]在本例中为 )。这段代码 - 它使用 pandas,而不是 BeautifulSoup,应该为您提供一个看起来像页面上的表格:

import pandas as pd  

all_tables = pd.read_html("http://indianindustriesdirectory.com/viewCompanyDetails.asp?compid=3855")

my_table = all_tables[5][[0,2]]
my_table.drop(my_table.tail(5).index,inplace=False).dropna(axis=0, how='all')

推荐阅读