2016-04-07 36 views
1

我想從此網頁獲取uniprot ID:ENSEMBL。但是我在使用xpath時遇到了問題。現在我得到一個空的列表,我不明白爲什麼。使用Xpath從網頁獲取字符串

我的想法是編寫一個採用ENSEMBL ID並返回uniprot ID的小函數。

import requests 
from lxml import html 
ens_code = 'ENST00000378404' 
webpage = 'http://www.ensembl.org/id/'+ens_code 

response = requests.get(webpage) 
tree = html.fromstring(response.content) 

path = '//*[@id="ensembl_panel_1"]/div[2]/div[3]/div[3]/div[2]/p/a' 

uniprot_id = tree.xpath(path) 

print uniprot_id 

任何幫助,將不勝感激:)

它只能打印現有列表,但仍返回Nonetype列表。

def getUniprot(ensembl_code): 

    ensembl_code = ensembl_code[:-1] 
    webpage = 'http://www.ensembl.org/id/'+ensembl_code 
    response = requests.get(webpage) 
    tree = html.fromstring(response.content) 
    path = '//div[@class="lhs" and text()="Uniprot"]/following-sibling::div/p/a/text()' 

    uniprot_id = tree.xpath(path) 
    if uniprot_id: 
     print uniprot_id 
     return uniprot_id 
+0

它返回None,因爲當你沒有匹配時,你的函數返回的結果是 –

+0

但是if語句如何得到它?我能做些什麼來避免它? – Suapu

+0

你應該檢查返回值,只是'返回tree.xpath(path)'而忘記if,然後檢查函數外部'ret = getUniprot(「whatever」)'然後'如果ret'使用它 –

回答

3

爲什麼你得到一個空列表是因爲它看起來像你使用的的XPath,當您右擊並選擇複製XPath鍍鉻提供,你的XPath返回沒什麼原因是因爲標籤不在源代碼中,它是動態生成的,因此請求返回的內容不包含元素。

In [6]: response = requests.get(webpage) 

In [7]: "ensembl_panel_1" in response.content 
Out[7]: False 

您應經常檢查網頁的源文件,看看有什麼你實際上得到回來,你在開發者控制檯看到什麼不一定,當你下載源代碼,你會得到什麼。

您還可以使用的情況下有在頁面上是其他http://www.uniprot.org/uniprot/一個特定的XPath,與"lhs"和文本Uniprot尋找一個類的div然後得到先上後下錨標記文本:

path = '//div[@class="lhs" and text()="Uniprot"]/following::a[1]/text()' 

這將使你:

['Q8TDY3'] 

您也可以選擇下面的兄弟DIV其中錨是它裏面的孩子p標籤:

path = '//div[@class="lhs" and text()="Uniprot"]/following-sibling::div/p/a/text()' 
+0

謝謝爲您的答案!我有另一個問題。如果我的ID導向到網頁,但我沒有這個路徑,因爲沒有UniprotID。我怎樣才能添加一個例外以避免未知的路徑?否則,它將返回一個空列表。澄清:在空列表後添加例外不允許我擺脫它,無論如何。我試過檢查長度和NoneType。 – Suapu

+0

沒有問題,如果沒有匹配的元素,只需檢查xpath返回的內容,'如果uniprot_id:'只有在找到匹配項時才爲真。你在循環中做這個嗎? –

+0

只需執行一次查找'uniprot_id = tree.xpath(path)'then'if uniprot_id' –