如何在Python中使用Beautiful Soup查找标签中包含2或3个单词的所有链接

2024-09-30 16:37:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Beautifulsoup从网站中提取iframe iframes=汤。全部找到('iframe') 我想找到iframe中包含2或3个单词的所有src标记 假设src链接如下"https://xyz.co/embed/TNagkx3oHj8/The.Tale.S001.true.72p.x264-QuebecRules" 我知道如何提取包含“xyz”的链接

srcs = []
 iframes = soup.find_all('iframe')
            for iframe in iframes:
                try:
                    if iframe['src'].find('xyz')>=0: srcs.append(iframe['src'])                 
                except KeyError: continue

我的问题是如何提取包含“xyz”等2个单词的所有链接 和“真”或3个字 这就像过滤器,如果这两个字不存在于该链接不要废掉它


Tags: https标记src网站链接embedfind单词
1条回答
网友
1楼 · 发布于 2024-09-30 16:37:56

您可以使用custom function来检查src是否包含您想要的所有单词。你知道吗

例如,您可以使用以下内容:

soup.find_all('iframe', src=lambda s: all(word in s for word in ('xyz', 'true')))

演示:

html = '''
    <iframe src="https://xyz.co/embed/TNagkx3oHj8/The.Tale.S001.true.72p.x264-QuebecRules">...</iframe>
    <iframe src="foo">...</iframe>
    <iframe src="xyz">...</iframe>
    <iframe src="xyz.true">...</iframe>
'''

soup = BeautifulSoup(html, 'html.parser')
iframes = soup.find_all('iframe', src=lambda s: all(word in s for word in ('xyz', 'true')))
print(iframes)

输出:

[<iframe src="https://xyz.co/embed/TNagkx3oHj8/The.Tale.S001.true.72p.x264-QuebecRules">...</iframe>, <iframe src="xyz.true">...</iframe>]

注意:

如果任何<iframe>标记不包含src属性,上述函数将引发错误。在这种情况下,将函数更改为:

soup.find_all('iframe', src=lambda s: s and all(word in s for word in ('xyz', 'true')))

相关问题 更多 >