码迷,mamicode.com
首页 > 编程语言 > 详细

python学习之----遍历单个域名和随机数

时间:2017-03-19 13:04:08      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:随机数   nbsp   url   with   idle   页脚   contact   style   代码   

    实现“维基百科六度分隔理论”的查找方法。也就是说,我们要实现从埃里克 · 艾德尔的词条页面(https://en.wikipedia.org/wiki/Eric_Idle)开始,经过最少的链接点击次数找到凯文 · 贝肯的词条页面(https://en.wikipedia.org/wiki/Kevin_Bacon)。

你应该已经知道如何写一段获取维基百科网站的任何页面并提取页面链接的Python 代码了:

from urllib.request import urlopen

from bs4 import BeautifulSoup

html = urlopen("http://en.wikipedia.org/wiki/Kevin_Bacon")

bsObj = BeautifulSoup(html)

for link in bsObj.findAll("a"):

if href in link.attrs:

print(link.attrs[href])

 

如果你观察生成的一列链接,就会看到你想要的所有词条链接都在里面:“Apollo 13”

“Philadelphia”和“Primetime Emmy Award”,等等。但是,也有一些我们不需要的链接:

//wikimediafoundation.org/wiki/Privacy_policy

//en.wikipedia.org/wiki/Wikipedia:Contact_us

其实维基百科的每个页面都充满了侧边栏、页眉、页脚链接,以及连接到分类页面、对话

页面和其他不包含词条的页面的链接:

/wiki/Category:Articles_with_unsourced_statements_from_April_2014

/wiki/Talk:Kevin_Bacon

最近我有个朋友在做一个类似维基百科采集这样的项目,他说为了判断维基百科的内链是

否链接到一个词条,他写了一个很大的过滤函数,超过100 行代码。不幸的是,可能在项

目启动的时候,他没有花时间去比较“词条链接”和“其他链接”的差异,也可能他后来

发现了那个技巧。如果你仔细观察那些指向词条页面(不是指向其他内容页面)的链接,

会发现它们都有三个共同点:

? 它们都在id 是bodyContent 的div 标签里

? URL 链接不包含分号

? URL 链接都以/wiki/ 开头

我们可以利用这些规则稍微调整一下代码来获取词条链接:

from urllib.request import urlopen

from bs4 import BeautifulSoup

import re

html = urlopen("http://en.wikipedia.org/wiki/Kevin_Bacon")

bsObj = BeautifulSoup(html)

for link in bsObj.find("div", {"id":"bodyContent"}).findAll("a",

href=re.compile("^(/wiki/)((?!:).)*$")):

if href in link.attrs:

print(link.attrs[href])

 

如果你运行代码,就会看到维基百科上凯文 ·贝肯词条里所有指向其他词条的链接。

当然,写程序来找出这个静态的维基百科词条里所有的词条链接很有趣,不过没什么实际

用处。我们需要让这段程序更像下面的形式。

? 一个函数getLinks,可以用维基百科词条/wiki/< 词条名称> 形式的URL 链接作为参数,

然后以同样的形式返回一个列表,里面包含所有的词条URL 链接。

? 一个主函数,以某个起始词条为参数调用getLinks,再从返回的URL 列表里随机选择

一个词条链接,再调用getLinks,直到我们主动停止,或者在新的页面上没有词条链接

了,程序才停止运行。

完整的代码如下所示:

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)

 

python学习之----遍历单个域名和随机数

标签:随机数   nbsp   url   with   idle   页脚   contact   style   代码   

原文地址:http://www.cnblogs.com/yintingting/p/6579681.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!