繁体   English   中英

无法从网页获取表格

[英]Can't get a table from a web page

我正在使用BeautifulSoup尝试从此URL获取所有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

结果,我只得到列的名称,而不是表本身。

我怎么能得到整个桌子。

内容是通过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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM