2017-08-30 22 views
0

APUからデータを取得しようとしていますが、応答としてプレーンテキストが取得されています。私はすべてのテキストを1行ずつ読みたい。Pythonのhttpリクエストからのテキスト応答を解析します。

これはurl変数です:http://www.amfiindia.com/spages/NAVAll.txt?t=23052017073640

まずスニペット:

from pymongo import MongoClient 
import requests 
from bs4 import BeautifulSoup as bs 
url = "https://www.amfiindia.com/spages/NAVAll.txt?t=23052017073640" 
request = requests.get(url) 
soup = bs(request.text,"lxml") 
for line in soup: 
    print line 
    break 

結果:それはテキスト全体

セカンドスニペットを出力します:

request = requests.get(url) 
for line in request.text(): 
    print line 
    break 

結果:例外:「ユニコード」オブジェクトは、私はラインでテキスト行を読み取ることができ、さらにいくつかの例を試してみましたが、していない

呼び出すことはできませんそれは1つの文字

request = requests.get(url) 
requestText = request.text() 
allMf = requestText.splitlines() 

結果を出力します。

+0

はあなたがループ() 'と'ないrequest.text'オーバーrequest.text '秒以上のスニペットでいることを確認していますか?また、 'request.text'はプロパティであり、メソッドではないので例外がスローされます。したがって、あなたは '()'を必要としません – Leva7

答えて

0

request.textは、メソッドではなくプロパティです。request.textは、ユニコード文字列を返します。request.text()は、エラー'unicode' object is not callableをスローします。

for line in request.text.splitlines(): 
    print line 
0

これを試してみてください:

from pymongo import MongoClient 
import requests 
from bs4 import BeautifulSoup as bs 
url = "https://www.amfiindia.com/spages/NAVAll.txt?t=23052017073640" 
request = requests.get(url) 
soup = bs(request.text,"lxml") 
for line in soup: 
    print line.text 
    break 
1
import requests 
from bs4 import BeautifulSoup as bs 
url = "https://www.amfiindia.com/spages/NAVAll.txt?t=23052017073640" 
request = requests.get(url) 
soup = bs(request.text,"lxml") 

# soup.text is to get the returned text 
# split function, splits the entire text into different lines (using '\n') and stores in a list. You can define your own splitter. 
# each line is stored as an element in the allLines list. 
allLines = soup.text.split('\n') 

for line in allLines: # you iterate through the list, and print the single lines 
    print(line) 
    break # to just print the first line, to show this works 
+0

あなたのコードを説明し、それがなぜ問題を解決するのか? *コードのみ*回答はそれほど役に立ちません。 – Zabuza

+0

説明が追加されました。 – RetardedJoker

関連する問題