问题:小白初学,《python网络数据采集》案例代码问题,其中这段代码中的“links”在运行中出现了NameError: name 'links' is not defined 的问题,刚刚以为是我编写出现了问题,但后来复制了书中的代码运行也是这样的问题,求解,谢谢。
代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import datetime
import random
import re
random.seed(datetime.datetime.now())
def getLinks(articleUrl):
html = urlopen("http://en.wikipedia.org"+articleUrl)
bsObj = BeautifulSoup(html)
return bsObj.find("div", {"id":"bodyContent"}).findAll("a",href=re.compile("^(/wiki/)((?!:).)*$"))
links = getLinks("/wiki/Kevin_Bacon")
while len(links) > 0:
newArticle = links[random.randint(0, len(links)-1)].attrs["href"]
print(newArticle)
links = getLinks(newArticle)
报错:
Traceback (most recent call last):
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python36-32/pc003.py", line 13, in
while len(links) > 0:
NameError: name 'links' is not defined
再次感谢!