【发布时间】:2016-04-07 16:13:54
【问题描述】:
我正在尝试从此网页获取 uniprot ID:ENSEMBL。但是我在使用 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
【问题讨论】:
-
它返回 None 因为这是你的函数在你没有匹配时返回的内容
-
但是if语句是怎么得到的呢?我能做些什么来避免它?
-
你应该检查返回值,只是
return tree.xpath(path),忘记if,然后在函数外检查,ret = getUniprot("whatever")然后if ret使用它
标签: python html xpath python-requests