我想用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/)((?!:).)*$"))
links
列表的长度永远不会达到0
,因此它将继续运行while循环,直到连接超时。你知道吗for循环之所以有效,是因为它在
range
上迭代,所以一旦达到范围最大值,它就会退出。你知道吗您从未解释过为什么要使用while循环,但是如果希望它在一定次数的迭代之后退出,则需要使用计数器。你知道吗
将打印上一页
相关问题 更多 >
编程相关推荐