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

标签 python python-3.x beautifulsoup bottle

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

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

环境

・Python 3.6.0

・ Bottle 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 循环之所以有效,是因为它在范围上进行迭代,因此一旦达到范围最大值,它将退出。

您从未解释过为什么要使用 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

关于python - 在for语句中,我能够得到预期的结果。但是为什么我用while语句却得不到预期的结果呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46762708/

相关文章:

python - 如何解决生成饼图时出现Python错误: ValueError: 'explode' must be of length 'x'

python - 有没有办法避免这种重复的代码?

python-3.x - 如何摆脱密码编译错误?

python - 使用 BeautifulSoup 抓取 Pantip 论坛

python-3.x - 在要抓取的网站上找不到 BeautifulSoup 的类名

python - 如何在 matplotlib 中为一个图形设置本地 rcParams 或 rcParams

python - 在python中传递一个方法

python - odoo10如何在1个字段中构建2个onchange函数

python - 导入 python 函数会出现 ModuleNotFoundError

python - beautifulsoup find_all() 导致无效日期