无法使用Python Beautifulsoup获取所有标签/文本来抓取网站

时间:2014-08-13 13:06:06

标签: python beautifulsoup

我遇到问题的项目涉及使用Python抓取网站(www.iasg.com)和#34; Beautifulsoup"。我是Python的初学者,虽然我以前在MATLAB的专家级编码(如果重要)。

我不确定我目前的问题是否是由于: 1.我没有正确登录到我试图浏览的网站 2.该网站编码严重,因此Beautifulsoup无法浏览所有标签

发生了什么:我尝试使用下面的代码来查看link

TD标签中的所有文字

当看到Beautifulsoup刮掉的东西时,很明显它不包括所有标签;要么由于没有正确登录,要么标签根本就没有。

import mechanize
import html5lib
import cookielib
from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup

def get_fund_links(url):
    html = urlopen(url).read()
    soup = BeautifulSoup(html)

    odd = []
    for item in soup.findAll('a', {'class':'small'}):
        odd.append(item["href"])

       fund_links = odd

    return fund_links

def get_fund(fund_url):
     html = urlopen(fund_url).read()
     soup = BeautifulSoup(html)
     program = []
     for item in soup.findAll('tr'):
         cols = item.findAll('td')
         for td in cols:
             program.append(td.text)

     return program

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

br.set_handle_equiv(True)
br.set_handle_gzip(False)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'IE')]

br.open('http://www.iasg.com/home/ctl/login?returnurl=%2f')

for f in br.forms():
    print f

br.select_form(nr=0)

user = br.form['dnn$ctr$Login$Login_DNN$txtUsername'] = 'yyyy'
passw = br.form['dnn$ctr$Login$Login_DNN$txtPassword'] = 'xxxx

br.submit()


result = get_fund_links('http://www.iasg.com/managed-futures/performance')
print get_fund(result[0])

print len(result[0])

1 个答案:

答案 0 :(得分:0)

使用我设置的用户名/密码尝试使用您的代码。您没有看到您想要的信息,因为它没有保持登录状态。我不熟悉机械化,但您的代码看起来过于复杂。也许请求模块会更简单,它会为您处理所有的cookie。

http://docs.python-requests.org/en/latest/

相关问题