Python,Mechanize |遇到登出问题

时间:2014-03-14 15:33:38

标签: python-2.7 mechanize

我正在学习python并使用mechanize运行我的第一个刮刀。

目标:登录网站,导航到网址列表并返回一大块文字,然后将其写入CSV。

我正在使用的代码工作得很好但是当我在列表中运行时,我遇到的问题是,在10到15行之后整个html页面将返回而不是那一大块文本。一旦发生错误,它将无法正常运行,直到我再次运行操作,但再次在10-15之后遇到障碍。

看着html看起来好像我已经退出了,无法找出原因。这些URL都是合法的,如果我单独为所有链接测试getNum它似乎工作正常。

最后一件事 - 该网站需要登录Javascript和cookie

以下是函数的外观

def get_Num(link): #takes in a URL, provided by the csv and finds the chunk of text I'm looking for
    import urllib2
    import cookielib
    import urllib
    import requests
    import mechanize

    # Browser
    br = mechanize.Browser()

    # Cookie Jar
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)

    # Browser options
    br.set_handle_equiv(True)
    br.set_handle_gzip(True)
    br.set_handle_redirect(True)
    br.set_handle_refresh(False)  
    br.set_handle_referer(True)
    br.set_handle_robots(False)

    # Follows refresh 0 but not hangs on refresh > 0
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

    # User-Agent (this is cheating, ok?)
    br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

    # The site we will navigate into, handling it's session
    br.open('https://www.website.com/login')

    #select the first form
    br.select_form(nr=0)

    #user credentials
    br['session_key'] = login
    br['session_password'] = pw

    # Login
    br.submit()
    print 'logged in'

    #open link
    br.open(link)
    html = br.response().read()
    position1 = html.find('text')
    position2 = html.find('>',position1)
    targetNumber = html[position1:position2]
    return targetNumber


def get_Info(inputFile,outputFile): # takes a CSV and runs getNum for ever url and then writes the whole thing to a csv
    import urllib2
    import re
    import csv

    with open(inputFile, "rb") as csvinput:
        with open(outputFile, 'w+') as csvoutput:
            reader = csv.reader(csvinput)
            writer = csv.writer(csvoutput)
            for rowNum, line in enumerate(reader):
                vv = getNum(str(line[1]))
                line.append(vv)

0 个答案:

没有答案
相关问题