How to extract certain strings when they occur adjacently with BeautifulSoup
<p>I'm parsing an HTML page's result from BeautifulSoup and the part(s) I'm interested in looks like this:</p>

<pre><code>&lt;i class="fa fa-circle align-middle font-80" style="color: #45C414; margin-right: 15px"&gt;&lt;/i&gt;Departure for &lt;a href="/en/ais/details/ports/17787/port_name:TEKIRDAG/_:3525d580eade08cfdb72083b248185a9" title="View details for: TEKIRDAG"&gt;TEKIRDAG&lt;/a&gt; &lt;/td&gt;
</code></pre>

<p>I'm interested in extracting the <code>port_name</code>, TEKIRDAG, however there are many port name's that are labeled identically. My question is is there a way to only extract <code>port_name</code> if it occers after the string <code>'Departure for'</code>?</p>

<p>You can locate the text node and get the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling" rel="nofollow">next sibling</a>:</p>

<pre><code>In [1]: from bs4 import BeautifulSoup

In [2]: data = """&lt;i class="fa fa-circle align-middle font-80" style="color: #45C414; margin-right: 15px"&gt;&lt;/i&gt;Departu
   ...: re for &lt;a href="/en/ais/details/ports/17787/port_name:TEKIRDAG/_:3525d580eade08cfdb72083b248185a9" title="Vie
   ...: w details for: TEKIRDAG"&gt;TEKIRDAG&lt;/a&gt; &lt;/td&gt;"""
   ...:     

In [3]: soup = BeautifulSoup(data, "html.parser")

In [4]: soup.find(text="Departure for ").next_sibling.get_text()
Out[4]: u'TEKIRDAG'
</code></pre>

python html beautifulsoup