使用python从获取的HTML代码中提取特定信息

时间:2016-04-16 07:22:48

标签: python html parsing beautifulsoup

我在python中相对较新。我需要一些生物信息学项目的建议。它是关于将某些酶ID转换为其他酶。

我已经做了什么以及什么有用,是从Rhea数据库中获取ID列表的html代码:

 53 url2 = "http://www.rhea-db.org/reaction?id=16952"
 54 f_xml2 = open("xml_tempfile2.txt", "w")
 55
 56 fetch2 = pycurl.Curl()
 57 fetch2.setopt(fetch2.URL, url2)
 58 fetch2.setopt(fetch.WRITEDATA, f_xml2)
 59 fetch2.perform()
 60 fetch2.close

所以HTML代码被保存到一个临时的txt文件中(我知道,可能不是最优雅的做事方式,但它适用于我;)。

现在我感兴趣的是HTML中的以下部分:

        <p>
            <h3>Same participants, different directions</h3>
            <div>
                <a href="./reaction?id=16949"><span>RHEA:16949</span></a>
                <span class="icon-question">myo-inositol + NAD(+) &lt;?&gt; scyllo-inosose + H(+) + NADH</span>
            </div><div>
                <a href="./reaction?id=16950"><span>RHEA:16950</span></a>
                <span class="icon-arrow-right">myo-inositol + NAD(+) =&gt; scyllo-inosose + H(+) + NADH</span>
            </div><div>
                <a href="./reaction?id=16951"><span>RHEA:16951</span></a>
                <span class="icon-arrow-left-1">scyllo-inosose + H(+) + NADH =&gt; myo-inositol + NAD(+)</span>
            </div>
        </p>

我想查看代码,直到到达“icon-arrow-right”类(此表达式在HTML中是唯一的)。然后我想从上面的行中提取“RHEA:XXXXXX”的信息。所以在这个例子中,我想以16950结束。

有一种简单的方法吗?我已经尝试过HTMLparser,但无法让它以某种方式工作,它会查找某个类,然后从上面的行中给我ID。

非常感谢你!

1 个答案:

答案 0 :(得分:1)

您可以使用BeautifulSoup之类的HTML解析器执行此操作:

>>> from bs4 import BeautifulSoup
>>> html = """ <p>
...             <h3>Same participants, different directions</h3>
...             <div>
...                 <a href="./reaction?id=16949"><span>RHEA:16949</span></a>
...                 <span class="icon-question">myo-inositol + NAD(+) &lt;?&gt; scyllo-inosose + H(+) + NADH</span>
...             </div><div>
...                 <a href="./reaction?id=16950"><span>RHEA:16950</span></a>
...                 <span class="icon-arrow-right">myo-inositol + NAD(+) =&gt; scyllo-inosose + H(+) + NADH</span>
...             </div><div>
...                 <a href="./reaction?id=16951"><span>RHEA:16951</span></a>
...                 <span class="icon-arrow-left-1">scyllo-inosose + H(+) + NADH =&gt; myo-inositol + NAD(+)</span>
...             </div>
...         </p>"""
>>> soup = BeautifulSoup(html, 'html.parser')
>>> soup.find('span', class_='icon-arrow-right').find_previous_sibling().get_text()
'RHEA:16950'
相关问题