python - 网络数据采集的例子,有关find函数等等的疑问
大家讲道理
大家讲道理 2017-04-18 09:53:50
0
2
472

来自 Python网络数据采集的例子:

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("p", {"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("p", {"id":"bodyContent"}).findAll("a", href=re.compile("^(/wiki/)((?!:).)*$"))

这段代码里面, find函数后面为什么可以加findAll,即写成 XXX.find().findAall() 的形式?

问题二:newArticle = links[random.randint(0, len(links)-1)].attrs["href"]
此段代码 像 links[].attrs[] 之类的写法是如何依据的?可以这样写的原理?

新人求教~~谢谢!

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回覆(2)
左手右手慢动作

推薦使用神箭手雲爬蟲( http://www.shenjianshou.cn ),完全在雲上編寫和執行爬蟲,不需要配置任何開發環境,快速開發快速實現。 

簡單幾行javascript 就可以實現複雜的爬蟲,同時提供許多功能函數:反反爬蟲、 js 渲染、資料發布、圖表分析、反防盜鍊等,這些在開發爬蟲過程中經常會遇到的問題都由神箭手幫你解決。 

大家讲道理

find函數返回的也是html文檔,可以接find函數和find_all函數;
數組取值後可以直接當作值的元素對待,例如:

a = ['ab',1,[1,2]]
a[0].upper() # 'AB'
a[2].append(1) # a == ['ab',1,[1,2,1]]
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板