Skip to main content
 首页 » 编程设计

Python beautifulsoup 抢表

2024年11月01日10rubylouvre

我正试图从该网页中获取表格。我不确定我是否捕获了正确的标签。这是我目前所拥有的。

from bs4 import BeautifulSoup 
import requests 
 
page='http://www.airchina.com.cn/www/en/html/index/ir/traffic/' 
 
r=requests.get(page) 
 
soup=BeautifulSoup(r.text) 
 
test=soup.findAll('div', {'class': 'main noneBg'}) 
rows=test.findAll("td") 

main noneBg 是表格吗?当我将鼠标悬停在该标签上时,它会突出显示表格吗?

请您参考如下方法:

您需要的表格位于从不同 URL 加载的 iframe 中。

以下是获取它的方法(注意 URL 不同):

from bs4 import BeautifulSoup 
import requests 
 
page = 'http://www.airchina.com.cn/www/jsp/airlines_operating_data/exlshow_en.jsp' 
 
r = requests.get(page) 
 
soup = BeautifulSoup(r.text) 
 
div = soup.find('div', class_='mainRight').find_all('div')[1] 
table = div.find('table', recursive=False) 
for row in table.find_all('tr', recursive=False): 
    for cell in row('td', recursive=False): 
        print cell.text.strip() 

打印:

Feb 2014 
% change vs Feb 2013 
% change vs Jan 2014 
Cumulative Feb 2014 
% cumulative change 
1.Traffic 
1.RTKs (in millions) 
1407.8 
... 

请注意,由于页面上的嵌套表格,您需要使用 recursive=False。