目前,我有一个问题,以避免“不要重复自己”。--这是我的代码--我想确切地说,我现在的情况是:
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发布于 2015-05-27 01:43:31
只需创建一个函数:
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')发布于 2015-05-27 05:58:58
这可能对你有用:
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 herehttps://stackoverflow.com/questions/30471747
复制相似问题