來自 Python網(wǎng)絡(luò)數(shù)據(jù)采集的例子:
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)
問題一: return bsObj.find("div", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!:).)*$"))
這段代碼里面, find函數(shù)后面為什么可以加findAll,即寫成 XXX.find().findAall() 的形式?
問題二:newArticle = links[random.randint(0, len(links)-1)].attrs["href"]此段代碼 像 links[].attrs[] 之類的寫法是如何依據(jù)的?可以這樣寫的原理?
新人求教~~謝謝!
網(wǎng)絡(luò)數(shù)據(jù)采集的例子,有關(guān)find函數(shù)等等的疑問
幕布斯6054654
2019-02-25 21:48:08