python3.x - 《python网络数据采集》案例代码问题
本文介绍了python3.x - 《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
再次感谢!
解决方案
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")#这里缩进问题
这篇关于python3.x - 《python网络数据采集》案例代码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文