我使用BeautifulSoup尝试从此网址获取所有2000家公司的整个表格:
https://www.forbes.com/global2000/list/#tab:overall 的
这是我写的代码:
from bs4 import BeautifulSoup
import urllib.request
html_content = urllib.request.urlopen('https://www.forbes.com/global2000/list/#header:position')
soup = BeautifulSoup(html_content, 'lxml')
table = soup.find_all('table')[0]
new_table = pd.DataFrame(columns=range(0,7), index = [0])
row_marker = 0
for row in table.find_all('tr'):
column_marker = 0
columns = row.find_all('td')
for column in columns:
new_table.iat[row_marker,column_marker] = column.get_text()
column_marker += 1
new_table
在结果中,我只得到列的名称,而不是表本身。
如何获得整张表格。
答案 0 :(得分:1)
内容是通过javascript
生成的,因此您必须selenium
模仿浏览器并滚动动作,然后使用beautiful soup
解析页面来源,或者在某些情况下,像这样,你可以通过查询他们的ajax API来访问这些值:
import requests
import json
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'}
target = 'https://www.forbes.com/ajax/list/data?year=2017&uri=global2000&type=organization'
with requests.Session() as s:
s.headers = headers
data = json.loads(s.get(target).text)
print([x['name'] for x in data[:5]])
输出(前5项):
['3M', '3i Group', '77 Bank', 'AAC Technologies Holdings', 'ABB']