2017-10-16 4 views
1

ウェブブラウザで「Web Scraping with Pytho code」の操作を確認したいと思います。 forステートメントでは、私は期待される結果を得ることができました。しかし、whileステートメントは、私は期待される結果を得ることができません。forステートメントでは、予想される結果を得ることができました。しかし、なぜ私はwhile文で期待される結果を得ることができないのですか?

環境

をウィキペディア

のURLを辿ってこすりは・Pythonの3.6.0

・0.13-devの

ボトル・mod_wsgiの-4.5.15

Apacheエラーログ

出力しない

ERR_EMPTY_RESPONSE。

スクレイピングはfor文で

index.py

from urllib.request import urlopen 
from bs4 import BeautifulSoup 
from bottle import route, view 
import datetime 
import random 
import re 

@route('/') 
@view("index_template") 

def index(): 
    random.seed(datetime.datetime.now()) 
    html = urlopen("https://en.wikipedia.org/wiki/Kevin_Bacon") 
    internalLinks=[] 
    links = getLinks("/wiki/Kevin_Bacon") 
    while len(links) > 0: 
     newArticle = links[random.randint(0, len(links)-1)].attrs["href"] 
     internalLinks.append(newArticle) 
     links = getLinks(newArticle) 
    return dict(internalLinks=internalLinks) 

def getLinks(articleUrl): 
    html = urlopen("http://en.wikipedia.org"+articleUrl) 
    bsObj = BeautifulSoup(html, "html.parser") 
    return bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!:).)*$")) 

の処理を終了しない

、私は期待どおりの結果を得ることができました。ウェブブラウザの出力

['/wiki/Michael_C._Hall', '/wiki/Elizabeth_Perkins', 
'/wiki/Paul_Erd%C5%91s', '/wiki/Geoffrey_Rush', 
'/wiki/Virtual_International_Authority_File'] 

index.py

from urllib.request import urlopen 
from bs4 import BeautifulSoup 
from bottle import route, view 
import datetime 
import random 
import re 
@route('/') 
@view("index_template") 
def index(): 
    random.seed(datetime.datetime.now()) 
    html = urlopen("https://en.wikipedia.org/wiki/Kevin_Bacon") 
    internalLinks=[] 
    links = getLinks("/wiki/Kevin_Bacon") 
    for i in range(5): 
     newArticle = links[random.randint(0, len(links)-1)].attrs["href"] 
     internalLinks.append(newArticle) 
    return dict(internalLinks=internalLinks) 
def getLinks(articleUrl): 
    html = urlopen("http://en.wikipedia.org"+articleUrl) 
    bsObj = BeautifulSoup(html, "html.parser") 
    return bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!:).)*$")) 
+0

が印刷されます、あなたはブレークポイントを追加し、それを取得どこまで見るためにあなたのコードを追跡しようとしたことがありますか?あるいは少なくともいくつかの 'print'文を追加して、それがどのような結果を取得しているのか見ることができます。 – Soviut

+0

また、問題に関連していないコードをすべて削除してください。 wsgiコード、ビューなどは、何に焦点を当てるべきかを理解することが難しくなっています。 – Soviut

+0

wsgiコードを削除します。 – re1

答えて

2

結果は、あなたのlinksリストの長さは、それが接続時間まで、whileループを実行していきます0に達することはありませんでる。

あなたのforループはrangeを反復しているので、範囲上限に達すると終了します。

なぜあなたはwhileループを使用しているのか説明したことはありませんが、一定の回数繰り返した後に終了したい場合は、カウンタを使用する必要があります。

counter = 0 

# this will exit on the 5th iteration 
while counter < 5: 
    print counter # do something 

    counter += 1 # increment the counter after each iteration 

直前は

0 1 2 3 4 
+0

私は、リンクリストの長さが0になったと誤解しました – re1

+0

リンクリストを持たないことを明確にするには、リンクのリストがあります;) – Soviut

関連する問題