【问题标题】: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?在 for 语句中,我能够得到预期的结果。但是为什么我不能用 while 语句得到预期的结果呢?
【发布时间】:2017-10-18 10:16:38
【问题描述】:

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

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

环境

・Python 3.6.0

・瓶子 0.13-dev

・mod_wsgi-4.5.15

Apache 错误日志

没有输出

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

【问题讨论】:

  • 您是否尝试过添加断点并跟踪您的代码以查看它有多远?或者至少添加一些 print 语句来查看它获取的结果是什么?
  • 另外,请删除所有与您的问题无关的代码。 wsgi 代码、视图等。它们让我们很难弄清楚应该关注什么。
  • 我删除了 wsgi 代码。

标签: python python-3.x beautifulsoup bottle


【解决方案1】:

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

【讨论】:

  • 我误会了,链表的长度由于追踪链接而达到了0
  • 只是为了清楚你没有链接列表,你有一个链接列表;)
猜你喜欢
  • 2023-03-06
  • 1970-01-01
  • 2015-01-20
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多