【问题标题】:BeautifulSoup find only elements where an attribute contains a sub-string? Is this possible?BeautifulSoup 仅查找属性包含子字符串的元素?这可能吗?
【发布时间】:2015-03-30 05:28:03
【问题描述】:

我在BeautifulSoup 代码中调用了find_all()。这目前可以让我获得所有图像,但如果我只想定位在其src 中具有“占位符”子字符串的图像,我该怎么做?

for t in soup.find_all('img'):  # WHERE img.href.contains("placeholder")

【问题讨论】:

  • 大概您的意思是src 属性,而不是href 属性?

标签: python html beautifulsoup html-parsing


【解决方案1】:

您可以在src 关键字参数中使用pass a function

for t in soup.find_all('img', src=lambda x: x and 'placeholder' in x):

或者,regular expression

import re

for t in soup.find_all('img', src=re.compile(r'placeholder')):

或者,用select()代替find_all()

for t in soup.select('img[src*=placeholder]'):

【讨论】:

  • 或使用 CSS 选择器:soup.select('img[src*=placeholder]').
  • @MartijnPieters 那我实际上也会这样做,谢谢 :) 我将包括在答案中。
猜你喜欢
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 2022-11-14
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多