python - 如何从beautifulsoup中的span标签中获取字符串
问题描述
我在将字符串从 beautifulsoup 中的 span 标签中取出时遇到问题。我尝试使用 text 属性,但这给了我一个 AttributeError: NoneType
object has no attribute text
。
source = requests.get("https://www.k-ruoka.fi/kauppa/tuotehaku").text
soup = BeautifulSoup(source, "lxml")
product = soup.find("ul", class_="product-grid")
for listt in product.find_all("li"):
kg = listt.find("span", class_="reference").text
print(kg)
上面的代码给出了 AttributeError。如果我不使用 .text 那么它给了我这个:
<span class="reference">1,58<span class="slash">/</span>kg</span>
但我只想要它的“1,58”和“kg”。
解决方案
您的代码有效,您只需要NoneType
在 for 循环中进行检查:
for listt in product.find_all("li"):
kg = listt.find("span", class_="reference")
if kg:
print(kg.text)
推荐阅读
- java - Web 与桌面应用程序的性能限制?
- javascript - aws Cognito UI 自定义未在反应 natvie 应用程序中更新
- loops - Ansible:如何遍历字典
- python - Pygame鼠标速度
- javascript - Knex 在 TypeScript 中的 OrderBy
- java - 为什么 int 和 float 在 Java 中可以一起操作?
- lisp - Portacle - 为什么当我访问文件时智能感知功能停止工作(它在 repl 中工作)
- dataframe - pyspark:删除重复值大于一个值
- javascript - 尝试开发 Chrome 扩展以自由更改 TimeZone,但它不起作用
- mongodb - 如何在 mongo db 中交换数组中的对象