在soup.find()方法中传递变量-Beautifulsoup Python [英] Pass variable in soup.find() method - Beautifulsoup Python

查看:391
本文介绍了在soup.find()方法中传递变量-Beautifulsoup Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在使用以下语法搜索元素:

Currently, I'm searching for elements using the below syntax:

priceele = soup.find(itemprop='price').string.strip()

实际上,该页面包含具有属性名称itemprop和值price <span> 元素.但是,我不需要寻找 <span> 元素,因为只有一个具有属性itemprop的元素.

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.

现在,我想要的是将itemprop='price'作为变量传递给soup.find()方法,因为我正在从数据库中动态加载这两件事.有可能吗?

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?

推荐答案

如果通过两件事"来引用属性的名称和值,则可以通过使用**运算符应用任意关键字来使它们动态化论点.例如:

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()

这篇关于在soup.find()方法中传递变量-Beautifulsoup Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆