我想知道我是否可以在字符串中给出一个可以传递给函数的关键字的参数列表?基本上,参数列表可能有也可能没有关键字,因此参数列表会有变量'types'。以下是我正在尝试做的一个例子:
from bs4 import BeautifulSoup
import urllib.request as urlreq
import my_parameters # can have variable values
# my_parameters.useful_token_concept = ["h1", "class_ = some_class"]
# I want to pass these above parameters into a function; "class_" is
# a keyword, but it's wrapped in a string => gives me problems
url = my_parameters.url
page = urlreq.urlope(url)
pageHtml = page.read()
page.close()
soup = BeautifulSoup(pageHtml)
# something like the following line works:
# params = soup.find("h1", class_ = "some_class")
params = soup.find(*my_parameters.useful_token_concept)
# params = soup.find(my_parameters.useful_token_concept[0],\
# my_parameters.useful_token_concept[1])
# I don't know how long the list of attributes/parameter-list to
# BeautifulSoup's find() function will be, nor do I know what keywords,
# if any, will be passed into find(), as given by a user to my_parameters.
print(params) # should print the html the user wants to scrape.
答案 0 :(得分:2)
为什么不使用更好的代表?即,而不是
my_parameters.useful_token_concept = ["h1", "class_ = some_class"]
使用
my_parameters.useful_token_concept = ["h1", {"class_": "some_class"}]
由于这些价值观'表示由您决定,使用dict
表示关键字参数比将它们编码为字符串然后必须解析该字符串要简单得多!
答案 1 :(得分:1)
您需要将令牌列表拆分为关键字参数字典和位置参数列表。
kwargs = {}
args = []
for i in my_parameters.useful_token_concept:
bits = i.split('=')
if len(bits) > 1:
kwargs[bits[0].strip()] = bits[1].strip()
else:
args.append(bits[0].strip())
params = soup.find(*args, **kwargs)
答案 2 :(得分:1)
您可以创建一个表示所有参数将如何传递的字符串表示,并使用eval()
将它们转换为您可以在实际函数调用中实际使用的内容:
my_parameters.useful_token_concept = ["h1", "class_ = some_class"]
def func_proxy(*args, **kwargs):
" Just return all positional and keyword arguments. "
return args, kwargs
calling_seq = ', '.join(my_parameters.useful_token_concept)
args, kwargs = eval('func_proxy({})'.format(calling_seq))
print('args:', args) # -> args: (<Header1 object>,)
print('kwargs:', kwargs) # -> kwargs: {'class_': <class '__main__.some_class'>}
parms = soup.find(*args, **kwargs)