BeautifulSoup的初学者,我正在尝试提取
公司名称,排名和收入从这个维基百科链接。
https://en.m.wikipedia.org/wiki/list_of_largest_internet_companies
到目前为止我使用的代码是:
from bs4 import BeautifulSoup
import requests
url = "https://en.wikiepdia.org"
req = requests.get(url)
bsObj = BeautifulSoup(req.text, "html.parser")
data = bsObj.find('table',{'class':'wikitable sortable mw-collapsible'})
revenue=data.findAll('data-sort-value')
我意识到即使是“数据”也不能正常工作,因为当我把它传递给flask网站时,它没有任何值。
有人可以建议一个修复和最优雅的方式来实现以上,以及一些建议的最佳方法,我们正在寻找的HTML时,刮痧(和格式)。
在这个链接上,https://en.m.wikipedia.org/wiki/list_of_largest_internet_companies我不确定要用来提取什么--是表类,div类还是体类。 此外,如何进行提取的链接和收入进一步向下的树。
我也试过:
data = bsObj.find_all('table', class_='wikitable sortable mw-collapsible')
它运行服务器,没有错误。 但是,网页“[]”上只显示一个空列表。
通常(并不总是)在处理维基百科表时,你不必费心处理BeautifulSoup。 就用熊猫吧:
import pandas as pd
table = pd.read_html('https://en.m.wikipedia.org/wiki/List_of_largest_Internet_companies')
table[0]
输出:
Rank Company Revenue ($B) F.Y. Employees Market cap. ($B) Headquarters Founded Refs
0 1 Amazon $280.5 2019 798000 $920.22 Seattle 1994 [1][2]
1 2 Google $161.8 2019 118899 $921.14 Mountain View 1998 [3][4]
等,然后可以使用标准的pandas方法选择或删除列等。
这里有一个使用BeautifulSoup的例子。 以下很多内容都是基于这里的答案https://stackoverflow.com/A/23377804/6873133。
from bs4 import BeautifulSoup
import requests
url = 'https://en.m.wikipedia.org/wiki/List_of_largest_Internet_companies'
req = requests.get(url)
bsObj = BeautifulSoup(req.text, 'html.parser')
data = bsObj.find('table',{'class':'wikitable sortable mw-collapsible'})
table_data = []
rows = data.find_all('tr')
for row in rows:
cols = row.find_all('td')
row_data = [ele.text.strip() for ele in cols]
table_data.append(row_data)
# First element is header so that is why it is empty
table_data[0:5]
# [[],
# ['1', 'Amazon', '$280.5', '2019', '798,000', '$920.22', 'Seattle', '1994', '[1][2]'],
# ['2', 'Google', '$161.8', '2019', '118,899', '$921.14', 'Mountain View', '1998', '[3][4]'],
# ['3', 'JD.com', '$82.8', '2019', '220,000', '$51.51', 'Beijing', '1998', '[5][6]'],
# ['4', 'Facebook', '$70.69', '2019', '45,000', '$585.37', 'Menlo Park', '2004', '[7][8]']]