Pass variable in soup.find() method - Beautifulsoup Python

梦想与她 提交于 2020-01-06 03:53:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!