源代码中的变量 - python编程

时间:2015-05-27 01:41:03

标签: python

目前我有一个问题需要避免并且不要重复自己"。 这是我的代码 - 我现在要重新确认我的情况:

if foo == 1:
   for node in content.findAll('a'):
       link = node.get('href')
elif foo == 2:
   for node in content.findAll('li'):
       link = node.li.get('title')

有什么方法可以这样做:(我知道在PHP中我可以做类似的事情)

if foo == 1:
   char = 'a'
   bar = "node.get('href')"
elif foo == 2:
   char = 'li'
   bar = "node.li.get('title')"

for node in content.findAll(char):
   link = bar

2 个答案:

答案 0 :(得分:0)

只需创建一个功能:

def findAll(content, char, get_code):
    for node in content.findAll(char):
        link = node.li.get(get_code)
    return link

然后,

if foo == 1:
    link = findAll(content, 'a', 'href')
elif foo == 2:
    link = findAll(content, 'a', 'title')

答案 1 :(得分:0)

这可能对您有用:

def find_link(content, entity, attribute, path=()):
    for node in content.findAll(entity):
        for part in path:
            node = getattr(node, part)
    return node.get(attribute)

这适用于单位:

# get attribute 'href' from 'a'
find_link(content, 'a', 'href')  

和嵌套搜索:

# get attribute 'attr' from div.ul.li
find_link(content, 'div', 'attr', path=['ul', 'li'])

以上试图模仿你的逻辑。因为这只找到最后一个链接, 这个版本可能会更好:

def find_link(content, entity, attribute, path=()):
    links = []
    for node in content.findAll(entity):
        for part in path:
            node = getattr(node, part)
        links.append(node.get(attribute))
    return links

它为您提供所有链接。

仅查找第一个链接可能如下所示:

def find_link(content, entity, attribute, path=()):
    for node in content.findAll(entity):
        for part in path:
            node = getattr(node, part)
        return node.get(attribute)
enter code here