擅长:python、mysql、java
<p>进行这种复杂匹配的最简单方法是<a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function" rel="noreferrer">write a function that performs the match</a>,并将函数作为<code>text</code>参数的值传入。在</p>
<pre><code>def must_contain_all(*strings):
def must_contain(markup):
return markup is not None and all(s in markup for s in strings)
return must_contain
</code></pre>
<p>现在可以得到匹配的字符串:</p>
^{pr2}$
<p>要获取包含字符串的标记,请使用.parent运算符:</p>
<pre><code>print [text.parent for text in soup.find_all(text=must_contain_all("world", "puzzle"))]
# [<p>Who in the world am I? Ah, that's the great puzzle.</p>]
</code></pre>