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

来自 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[] 之类的写法是如何依据的?可以这样写的原理?

新人求教~~谢谢!

大家讲道理
大家讲道理

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

Antworte allen(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]]
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage