Python beautifulsoup没有抓住全桌

时间:2014-04-22 07:35:23

标签: python beautifulsoup mechanize

由于mechanize

,我不确定这是不是抓住了整个表格

这有效:

from bs4 import BeautifulSoup
import requests

page = 'http://www.airchina.com.cn/www/jsp/airlines_operating_data/exlshow_en.jsp'
r = requests.get(page)

r.encoding = 'utf-8'
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.split()

但这不是:

import mechanize
from bs4 import BeautifulSoup
import requests

URL='http://www.airchina.com.cn/www/jsp/airlines_operating_data/exlshow_en.jsp'
control_year=['2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014']
control_month=['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']

br = mechanize.Browser()
r=br.open(URL)

br.select_form("exl")
control_m = br.form.find_control('month')
control_y = br.form.find_control('year')

br[control_m.name]=['06'] 
br[control_y.name]=['2012']
response = br.submit()
soup = BeautifulSoup(response,'html.parser')
#div = soup.find('div', class_='mainRight')


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()

使用mechanize的人只生成以下内容,即使在萤火虫中我看到所有trtd

Jun 2012
% change vs Jun 2011
% change vs May 2012
Cumulative Jun 2012
% cumulative change

1 个答案:

答案 0 :(得分:1)

将两者结合使用时没有任何问题,因此可能与您正在使用的html.parser有关。

import mechanize
from bs4 import BeautifulSoup

URL = ('http://www.airchina.com.cn/www/jsp/airlines_operating_data/'
       'exlshow_en.jsp')
control_year = ['2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013',
                '2014']
control_month = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10',
                 '11', '12']

br = mechanize.Browser()
r = br.open(URL)

br.select_form("exl")
control_m = br.form.find_control('month')
control_y = br.form.find_control('year')

br[control_m.name] = ['06']
br[control_y.name] = ['2012']
response = br.submit()

soup = BeautifulSoup(response)

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.split()