2016-03-07 175 views
0

我已經寫下了一段代碼,以從html文件中提取一些文本。此代碼從網頁中提取所需的行,現在我要提取序列數據。不幸的是,我無法提取文本,它顯示出一些錯誤。從html文件中提取文本python

import urllib2 
from HTMLParser import HTMLParser 
import nltk 
from bs4 import BeautifulSoup 

# Proxy information were removed 
# from these two lines 

proxyOpener = urllib2.build_opener(proxyHandler) 
urllib2.install_opener(proxyOpener) 

response = urllib2.urlopen('http://tuberculist.epfl.ch/quicksearch.php?gene+name=Rv0470c') 

################## BS Block ################################ 

soup = BeautifulSoup(response) 
text = soup.get_text() 
print text 

########################################################## 

html = response.readline() 

for l in html: 
    if "|Rv0470c|" in l: 
     print l  # code is running successfully till here 

raw = nltk.clean_html(html) 
print raw 

如何成功運行此代碼?我已經檢查了所有可用的線程和解決方案,但沒有任何工作。

我想提取這一部分:

M. tuberculosis H37Rv|Rv0470c|pcaA 
MSVQLTPHFGNVQAHYDLSDDFFRLFLDPTQTYSCAYFERDDMTLQEAQIAKIDLALGKLNLEPGMTLLDIGCGWGATMRRAIEKYDVNVVGLTLSENQAGHVQKMFDQMDTPRSRRVLLEGWEKFDEPVDRIVSIGAFEHFGHQRYHHFFEVTHRTLPADGKMLLHTIVRPTFKEGREKGLTLTHELVHFTKFILAEIFPGGWLPSIPTVHEYAEKVGFRVTAVQSLQLHYARTLDMWATALEANKDQAIAIQSQTVYDRYMKYLTGCAKLFRQGYTDVDQFTLEK 
+0

什麼是錯誤? – mvelay

+0

這是錯誤「NotImplementedError:要刪除HTML標記,請使用BeautifulSoup的get_text()函數」 然後我嘗試使用BeutifulSoup,但其返回的文本作爲數百萬單個字符,而不是正確的文本 – jax

+0

請[編輯]您的問題,並告訴我們你對BS的使用。 – 2016-03-07 09:11:57

回答

0

我能夠寫下這個代碼後,提取所需的文字:沒有任何依賴關係接受「的urllib2」和我的情況下,它就像一個魅力哪些工作。

import urllib2 

httpProxy = {'username': '------', '-----': '-------', 'host': '------', 'port': '-----'} 
proxyHandler = urllib2.ProxyHandler({'http': 'http://'+httpProxy['username']+':'+httpProxy['password']+'@'+httpProxy['host']+':'+httpProxy['port']}) 
proxyOpener = urllib2.build_opener(proxyHandler) 
urllib2.install_opener(proxyOpener) 



response = urllib2.urlopen('http://tuberculist.epfl.ch/quicksearch.php?gene+name=Rv0470c') 

html = response.readlines() 

f = open("/home/zebrafish/Desktop/output.txt",'w') 


for l in html: 
    if "|Rv0470c|" in l: 
     l = l.split("</small>")[0].split("<TR><TD><small style=font-family:courier>")[1] 
     l = l.split("<br />") 
     ttl = l[:1] 
     seq = "".join(l[1:]) 
     f.write("".join(ttl)) 
     f.write(seq) 
f.close() 
0

我不太肯定正是您所要求作爲一個整體,但這裏是我的臨時採取對您的問題(類似於你其實)這確實檢索您請求的HTML的一部分。也許你可以得到一些想法。 (針對Python2進行調整)

import requests 
from bs4 import BeautifulSoup 

url = 'http://tuberculist.epfl.ch/quicksearch.php?gene+name=Rv0470c' 
r = requests.get(url) 
html = r.content 
soup = BeautifulSoup(html, "lxml") 
for n in soup.find_all('tr'): 
    if "|Rv0470c|" in n.text: 
     nt = n.text 
     while '\n' in nt: 
      nt.replace('\n','\t') 
     nt=nt.split('\t') 
     nt = [x for x in nt if "|Rv0470c|" in x][0].strip() 
     print (nt.lstrip('>'))