简体   繁体   中英

Pass parameter into Python function

I have a function that accepts a Beautiful Soup object, soup .

I also want to pass it a variable telling it what to do with soup . Right now the function is:

def get_info(soup):
    info = soup.findAll('div',{'id':'hideinse'})[0]('a',href=True)
    #do stuff

But what I want to do is pass in this line findAll('div',{'id':'hideinse'})[0]('a',href=True) and not as a bunch of strings. I want it not to always be findAll and such, so want I'm trying to do but not sure how is:

def get_ifno(soup, parse_line):
     info = soup.parse_line
     #do stuff

So how can I pass that in?

Given the complexity of what you want you should take a function in that the caller can provide:

def get_info(soup, parse_line):
    info = parse_line(soup)

get_info(soup, lambda x: x.findAll('div',{'id':'hideinse'})[0]('a',href=True))

Your can probably get the most flexibility with the least amount of headache by passing lambdas:

def get_info(callback):
    info = callback()

get_info(lambda: soup.findAll('div',{'id':'hideinse'})[0]('a',href=True))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM