爬遍整个域名

   六度空间理论:任何两个陌生人之间所间隔的人不会超过六个,也就是说最多通过五个人你可以认识任何一个陌生人。通过维基百科我们能够通过连接从一个人连接到任何一个他想连接到的人。

1. 获取一个界面的所有连接

 from urllib.request import urlopen
from bs4 import BeautifulSoup html = urlopen("http://en.wikipedia.org/wiki/Kevin_Bacon")
bsObj = BeautifulSoup(html,'html.parser')
for link in bsObj.find_all("a"):
if 'href' in link.attrs:
print(link.attrs['href'])

2. 获取维基百科当前人物关联的事物

1. 除去网页中每个界面都会存在sidebar,footbar,header links 和 category pages,talk pages.

2. 当前界面连接到其他界面的连接都会有的相同点

I 包含在一个id为bodyContent的div中

II 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,"html.parser")
for link in bsObj.find('div',{"id":"bodyContent"}).find_all("a",href=re.compile("^(/wiki/)((?!:).)*$")):
if 'href' in link.attrs:
print(link.attrs['href'])

3. 深层查找

简单的从一个维基百科界面中找到当前界面的连接是没有意义的,如果能够从当前界面开始循环的找下去会有很大的进步

1. 需要创建一个简单的方法,返回当前界面所有文章的连接

2. 创建一个main方法,从一个界面开始查找,然后进入其中一个随机连接,以这个新连接为基础继续查找直到没有新的连接为止。

from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
from random import choice
import re basename = "http://en.wikipedia.org" def getLinks(pagename):
url = basename + pagename
try:
with urlopen(url) as html:
bsObj = BeautifulSoup(html,"html.parser")
links = bsObj.find("div",{"id":"bodyContent"}).find_all("a",href=re.compile("^(/wiki/)((?!:).)*$"))
return [link.attrs['href'] for link in links if 'href' in link.attrs]
except (HTTPError,AttributeError) as e:
return None def main():
links = getLinks("/wiki/Kevin_Bacon")
while len(links) > 0:
nextpage = choice(links)
print(nextpage)
links = getLinks(nextpage) main()

4. 爬遍整个域名

1. 爬遍整个网站首先需要从网站的主界面开始

2. 需要保存已经访问过的网页,避免重复访问相同的地址

from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
from random import choice
import re basename = "http://en.wikipedia.org"
visitedpages = set()#使用set来保存已经访问过的界面地址 def visitelink(pagename):
url = basename + pagename
global visitedpages
try:
with urlopen(url) as html:
bsObj = BeautifulSoup(html,"html.parser")
links = bsObj.find("div",{"id":"bodyContent"}).find_all("a",href=re.compile("^(/wiki/)((?!:).)*$"))
for eachlink in links:
if 'href' in eachlink.attrs:
if eachlink.attrs['href'] not in visitedpages:
nextpage = eachlink.attrs['href']
print(nextpage)
visitedpages.add(nextpage)
visitelink(nextpage)
except (HTTPError,AttributeError) as e:
return None visitelink("")

5. 从网站上搜集有用信息

1. 没做什么特别的东西,在访问网页的时候打印了一些 h1和文字内容

2. 在print的时候出现的问题》

UnicodeEncodeError: 'gbk' codec can't encode character u'\xa9' in position 24051: illegal multibyte sequence

   解决方法:在print之前将source_code.encode('GB18030')

解释:GB18030是GBK的父集,所以能兼容GBK不能编码的字符。

from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
from random import choice
import re basename = "http://en.wikipedia.org"
visitedpages = set()#使用set来保存已经访问过的界面地址 def visitelink(pagename):
url = basename + pagename
global visitedpages
try:
with urlopen(url) as html:
bsObj = BeautifulSoup(html,"html.parser")
try:
print(bsObj.h1.get_text())
print(bsObj.find("div",{"id":"mw-content-text"}).find("p").get_text().encode('GB18030'))
except AttributeError as e:
print("AttributeError")
links = bsObj.find("div",{"id":"bodyContent"}).find_all("a",href=re.compile("^(/wiki/)((?!:).)*$"))
for eachlink in links:
if 'href' in eachlink.attrs:
if eachlink.attrs['href'] not in visitedpages:
nextpage = eachlink.attrs['href']
print(nextpage)
visitedpages.add(nextpage)
visitelink(nextpage)
except (HTTPError,AttributeError) as e:
return None visitelink("")

python 爬虫(三)的更多相关文章

  1. Python爬虫(三)爬淘宝MM图片

    直接上代码: # python2 # -*- coding: utf-8 -*- import urllib2 import re import string import os import shu ...

  2. python爬虫(三)

    Requests模块 这个库的标准文档有个极其幽默的地方就是它的中文翻译,我就截取个开头部分,如下图: 是不是很搞笑,在正文中还有许多,管中窥豹,可见一斑.通过我的使用,感觉Requests库的确是给 ...

  3. Python 爬虫三 beautifulsoup模块

    beautifulsoup模块 BeautifulSoup模块 BeautifulSoup是一个模块,该模块用于接收一个HTML或XML字符串,然后将其进行格式化,之后遍可以使用他提供的方法进行快速查 ...

  4. Python爬虫(三)——开封市58同城出租房决策树构建

    决策树框架: # coding=utf-8 import matplotlib.pyplot as plt decisionNode = dict(boxstyle=') leafNode = dic ...

  5. Python爬虫(三)——对豆瓣图书各模块评论数与评分图形化分析

    文化         经管 ....略 结论: 一个模块的评分与评论数相关,评分为 [8.8——9.2] 之间的书籍评论数往往是模块中最多的

  6. Python 爬虫 (三)

    #对第一章的百度翻译封装的函数进行更新 1 from urllib import request, parse from urllib.error import HTTPError, URLError ...

  7. Python爬虫(四)——开封市58同城数据模型训练与检测

    前文参考: Python爬虫(一)——开封市58同城租房信息 Python爬虫(二)——对开封市58同城出租房数据进行分析 Python爬虫(三)——对豆瓣图书各模块评论数与评分图形化分析 数据的构建 ...

  8. Python爬虫(四)——豆瓣数据模型训练与检测

    前文参考: Python爬虫(一)——豆瓣下图书信息 Python爬虫(二)——豆瓣图书决策树构建 Python爬虫(三)——对豆瓣图书各模块评论数与评分图形化分析 数据的构建 在这张表中我们可以发现 ...

  9. Python爬虫学习:三、爬虫的基本操作流程

    本文是博主原创随笔,转载时请注明出处Maple2cat|Python爬虫学习:三.爬虫的基本操作与流程 一般我们使用Python爬虫都是希望实现一套完整的功能,如下: 1.爬虫目标数据.信息: 2.将 ...

  10. 3.Python爬虫入门三之Urllib和Urllib2库的基本使用

    1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它是一段HTML代码,加 JS.CSS ...

随机推荐

  1. ubuntu 12.04 LTS 64位兼容运行32位程序

    安装完Goagent,运行的时候出现了问题,在网络上翻看一些关于ubuntu的文档时,突然记起自己安装的是64位版,而goagent应该是32位的,于是通过sudo apt-get install i ...

  2. Id.value与document.getElementById("Id").value的区别

    如果标签Id在Form表单里面的话,直接Id.value就不能用了,而是要用Form.Id.value来取值或设置值 所以最好用document.getElementById("Id&quo ...

  3. 【bzoj1606】[Usaco2008 Dec]Hay For Sale 购买干草

    题目描述 约翰遭受了重大的损失:蟑螂吃掉了他所有的干草,留下一群饥饿的牛.他乘着容量为C(1≤C≤50000)个单位的马车,去顿因家买一些干草.  顿因有H(1≤H≤5000)包干草,每一包都有它的体 ...

  4. iis虚拟目录实现分布式文件服务器

    前提:假定有2台服务器:服务器a和服务器b,则服务器a和b须在同一局域网内 服务器设定:a为web服务器,b为文件服务器.这里服务器环境是:Windows Server 2008 R2 大致步骤如下: ...

  5. dom 无法找到 body节点问题

    最近在学习html dom节点知识时候,对照代码自己敲了一边,始终获取不到文档中的body对象,代码如下(未修改前): <!doctype html> <html> <h ...

  6. JavaScript的模块化之AMD&CMD规范

    前端开发常常会遇到的问题: 1.恼人的命名冲突: 2.繁琐的文件依赖: 模块化开发的优势: 1.解决命名冲突和依赖管理: 2.模块的版本管理: 3.提高代码的可维护性: 4.前端性能优化: JavaS ...

  7. Markdown简单语法

    Content 标题大小 斜体和加粗 分割线 有序列表和无序列表 链接 代码框 标题大小 在字体下方加上-和=分别表示一级标题和二级标题,例如: 一级标题 --- 二级标题 === 或者使用#的个数表 ...

  8. MyBatis:统计数量

    dao: /** * 统计商家的案例数量 * * @param shopId * @return */ long countByShopId(Long shopId); @Override publi ...

  9. vs2012 安装entity framework

    1.安装vs2012 2.打开vs2012的工具下的扩展工具 3.搜索nuget,没安装的直接在线安装 4.安装好了NuGet,程序包管理器控制台 5.执行命令Install-Package Enti ...

  10. Xcode工作区间xxxx.xcworkspace不包含xxxx.xcodeproj

    一.问题描述 项目用到cocoapods管理第三方框架,所以需要打开xxxx.xcworkspace,Pods正常显示,但xxxx.xcodeproj显示红色,不包含xxxx.xcodeproj并且无 ...