《python网络数据采集》案例代码问题

问题:小白初学,《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 <module>
    while len(links) > 0:
NameError: name 'links' is not defined

再次感谢!

阅读 3.5k
1 个回答
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")#这里缩进问题
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进