问题
Currently, I'm searching for elements using the below syntax:
priceele = soup.find(itemprop='price').string.strip()
Actually, the page contains <span> element having attribute name itemprop with value price. But, I don't need to look for <span> element because there is only one element with attribute itemprop.
Now, what I want is to pass itemprop='price' as a variable to soup.find() method becausing I'm loading these two things from database dynamically. Is it possible?
回答1:
If by "two things" you refer to the name and value of the attribute, you can make them dynamic by using the ** operator to apply arbitrary keyword arguments. For example:
attrname = 'itemprop'
attrvalue = 'price'
search = {attrname: attrvalue}
priceele = soup.find(**search).string.strip()
来源:https://stackoverflow.com/questions/25075310/pass-variable-in-soup-find-method-beautifulsoup-python