python - BeautifulSoup 只查找属性包含子字符串的元素?这可能吗?

标签 python html beautifulsoup html-parsing

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

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

最佳答案

您可以 pass a functionsrc 关键字参数中:

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')):

或者,不使用 find_all(),而是使用 select() :

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

关于python - BeautifulSoup 只查找属性包含子字符串的元素?这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28240956/

相关文章:

python - 插入具有复合主键的模型时出现 IntegrityError

css - 如何仅使用 CSS 填充拇指左侧的 HTML5 input[type=range]?

python - Mechanize 和 Beautifulsoup httplib.InvalidURL : nonnumeric port: '' (Python) 错误

python - 继续并通过 : what's the difference?

Python:错误 - tabula-py 无法读取 PDF

javascript - 将 jquery 值绑定(bind)到特定的 DIV 高度

html - 如何禁用事件链接的悬停效果?

python - 如何编写一个 BeautifulSoup 过滤器,它只解析标签之间带有特定文本的对象?

python - 如何提取 HTML 段落的某些部分

python - 使用正则表达式避免 pandas str.replace