我想检查'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/