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

2024-05-02 05:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用web浏览器检查“Web Scraping with Pytho code”的操作。在for语句中,我能够得到预期的结果。但是while语句,我不能得到预期的结果。你知道吗

通过追踪维基百科的网址

环境

・Python 3.6.0版

・瓶子0.13-dev

・国防部wsgi-4.5.15

Apache错误日志

No output

ERR_EMPTY_RESPONSE.  

刮削不能完成加工

索引.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语句中,我能够得到预期的结果。你知道吗

web浏览器输出结果

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

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

Tags: fromimportreviewdatetimehtmlwikirandom
1条回答
网友
1楼 · 发布于 2024-05-02 05:21:54

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

相关问题 更多 >