How can I find one tag between two other tags?
<p>I have a document with structure like this:</p>

<pre><code>&lt;tag1&gt;some_text_1&lt;/tag1&gt;
&lt;tag2&gt;text_1&lt;/tag2&gt;
&lt;tag3&gt;....&lt;/tag3&gt;
&lt;tag2&gt;text_2&lt;/tag2&gt;
&lt;tag1&gt;some_text_2&lt;/tag1&gt;
&lt;tag2&gt;text_3&lt;/tag2&gt;
...
</code></pre>

<p>And I need to get all <code>tag2</code> instances that are after <code>tag1</code> with <code>some_text_1</code> and before the next <code>tag1</code>.</p>

<p>Your description  <em>I need to get all tag2 instances that are after tag1 with some_text_1 and before the next tag2.</em> basically equates to getting the first <code>tag2</code> after any tag1 with the text <code>some_text_</code>.</p>

<p>So find the <code>tag1's</code> with the certain text and check if the next sibling tag is a <code>tag2</code>, if it is pull the tag2:</p>

<pre><code>html = """&lt;tag1&gt;some_text_1&lt;/tag1&gt;
&lt;tag2&gt;text_1&lt;/tag2&gt;
&lt;tag3&gt;....&lt;/tag3&gt;
&lt;tag2&gt;text_2&lt;/tag2&gt;
&lt;tag1&gt;some_text_2&lt;/tag1&gt;
&lt;tag2&gt;text_3&lt;/tag2&gt;"""


def get_tags_if_preceded_by(soup, tag1, tag2, text):
    for t1 in soup.find_all(tag1, text=text):
        nxt_sib = t1.find_next_sibling()
        if nxt_sib and nxt_sib.name == tag2:
            yield nxt_sib

soup = BeautifulSoup(html, "lxml")

print(list(get_tags_if_preceded_by(soup, "tag1", "tag2", "some_text_1")))
</code></pre>

<p>If it does not have to be directly after, it actually makes it simpler, you just need to search for a specific <code>tag2</code> sibling:</p>

<pre><code>def get_tags_if_preceded_by(soup, tag1, tag2, text):
    for t1 in soup.find_all(tag1, text=text):
        nxt_sib = t1.find_next_sibling(t2)
        if nxt_sib:
            yield nxt_sib
</code></pre>

<p>If you really want to find tags between two tags specifically, you can use the logic in <a href="http://stackoverflow.com/questions/38290588/extracting-html-between-tags/38290786#38290786">this answer</a>.</p>

python python-3.x beautifulsoup