Python beautifulsoup 抢表

标签 python beautifulsoup

我正在尝试从此网页中获取表格。我不确定我是否捕获了正确的标签。这是我到目前为止所拥有的。

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

关于Python beautifulsoup 抢表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22812536/

相关文章:

python - 在 python 中使用 beautifulsoup 有问题

java - 将 scipy 与 java 集成

python - 网站开发的设置过程是怎样的?

python - 使用 Python/BeautifulSoup 迭代 .txt 文件中的多个 URL

python - BeautifulSoup 只获取 td 标签中的 "general"文本,嵌套标签中没有任何内容

html - 用 beautifulsoup 选择元素

python - 在 centos7 上安装 pip(3) 的推荐方法

python - 将带有分隔符的数据框展平为变量

c++ - 使用 Python/C API 在 Python-List 上使用 C++-Iterators?

python - 如何在没有多余换行符的情况下从 BeautifulSoup 输出 XML?