![](/img/trans.png)
[英]Extracting specific Information from a website using BeautifulSoup (Python)
[英]Extracting specific information from fetched HTML code using python
我是python中的一個相對較新的人。 我需要一些關於生物信息學項目的建議。 這是關於將某些酶 ID 轉換為其他酶 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(+) <?> 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(+) => 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 => myo-inositol + NAD(+)</span>
</div>
</p>
我想通過代碼直到達到類“icon-arrow-right”(這個表達式在 HTML 中是唯一的)。 然后我想從上面的行中提取“RHEA:XXXXXX”的信息。 所以在這個例子中,我想以 16950 結束。
有沒有一種簡單的方法可以做到這一點? 我已經嘗試過 HTMLparser,但無法讓它以查找某個類的方式工作,然后從上面的行中給我 ID。
非常感謝您提前!
您可以使用像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(+) <?> 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(+) => 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 => 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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.