第三章 p28
书中源代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import datetime
import random
random.seed(datetime.datetime.now())
def getLinks(articleUrl):
html = urlopen("http://www.baike.com"+articleUrl)
bsObj = BeautifulSoup(html, 'html.parser')
return bsObj.findAll("a", {'class':'innerlink'})
links = getLinks("/wiki/%E5%B0%8F%E6%A0%97%E6%97%AC&prd=so_1_doc")
print(len(links))
while len(links) > 0:
newArticle = links[random.randint(0, len(links)-1)].attrs['href']
print(newArticle)
links = getLinks(newArticle)
注意书中最后一行inks = getLinks(newArticle) 传给getLinks的是一个完整的URL
在这里我们应该读取/wiki/以及之后的内容,所以改成 links = getLinks(newArticle[20:])
20 即为http://www.baike.com 的长度