爬遍整个域名

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

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. Sql Server随机取数据

    select top 10 * from tablename order by NEWID()

  2. Notepad++源码编译及其分析

    Notepad++是一个小巧精悍的编辑器,其使用方法我就不多说了,由于notepad++是使用c++封装的windows句柄以及api来实现的,因此对于其源码的研究有助于学习如何封装自己简单的库(当然 ...

  3. CSS Sprites优缺点

    利用CSS Sprites能很好地减少网页的http请求,从而大大的提高页面的性能,这也是CSS Sprites最大的优点,也是其被广泛传播和应用的主要原因: CSS Sprites能减少图片的字节, ...

  4. MySQL报错:Got error 28 from storage engine

    今天碰到数据库出错: Got error 28 from storage engine 查了一下,数据库文件所在的盘应该没事,应该是数据库用的临时目录空间不够 问题原因: 磁盘临时空间不够导致. 解决 ...

  5. word20161218

    QoS, Quality of Service / 服务质量 QoS Admission Control Service / QoS 许可控制服务 Quality of Service, QoS / ...

  6. PYTHON map()函数详解

    map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回. 栗子如下↓ 图片来自于网上 def f(x,a): return x+x ...

  7. python address already in use

    1)找到使用端口的进程pid netstat -lp 2)kill掉pid kill -9 1234

  8. 如何方便的保存WinForm窗体控件的位置大小等等配置信息

    由于分辨率.屏幕主题.字体大小的不同,窗体显示效果在不同机器上不尽相同.窗体的弹性设计并不能满足多样的需求.为保证在各种情况下,能有满意的效果.窗体的多样显示方式能改变,并且保存.载入配置,显得很重要 ...

  9. WPF DataGrid 性能加载大数据

    WPF(Windows Presentation Foundation)应用程序在没有图形加速设备的机器上运行速度很慢是个公开的秘密,给用户的感觉是它太吃资源了,WPF程序的性能和硬件确实有很大的关系 ...

  10. gnu coreutils-8.25 for win32 static - Beta

    gnu.win32-coreutils-8.25.7z 2.7 Mb bc-1.06.tar.gz coreutils-8.25.tar.xz diffutils-3.5.tar.xz gawk-4. ...