【发布时间】: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