在 for 语句中,我能够得到预期的结果。但是为什么while语句得不到预期的结果呢?

In the for statement, I was able to get the expected results. But why can not I get the expected results with the while statement?

我想用网络浏览器检查“Web Scraping with Pytho code”的运行情况。在 for 语句中,我能够得到预期的结果。但是while语句,我无法得到预期的结果。

通过追踪维基百科的 url 进行抓取

环境

・Python 3.6.0

・瓶子 0.13-dev

・mod_wsgi-4.5.15

Apache 错误日志

No output

ERR_EMPTY_RESPONSE.  

抓取未完成处理

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/)((?!:).)*$"))

在for语句中,我能够得到预期的结果。

网络浏览器输出结果

['/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/)((?!:).)*$"))

您的 links 列表的长度永远不会达到 0 因此它将继续 运行 while 循环直到连接超时。

您的 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