python 爬虫(三)

爬遍整个域名

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

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

1 from urllib.request import urlopen
2 from bs4 import BeautifulSoup
3
4 html = urlopen("http://en.wikipedia.org/wiki/Kevin_Bacon")
5 bsObj = BeautifulSoup(html,‘html.parser‘)
6 for link in bsObj.find_all("a"):
7     if ‘href‘ in link.attrs:
8         print(link.attrs[‘href‘])

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

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

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

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

II url中不包含分号,并且以/wiki/开头

1 from urllib.request import urlopen
2 from bs4 import BeautifulSoup
3 import re
4
5 html = urlopen("http://en.wikipedia.org/wiki/Kevin_Bacon")
6 bsObj = BeautifulSoup(html,"html.parser")
7 for link in bsObj.find(‘div‘,{"id":"bodyContent"}).find_all("a",href=re.compile("^(/wiki/)((?!:).)*$")):
8     if ‘href‘ in link.attrs:
9         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("")

时间: 2024-08-09 06:19:51

python 爬虫(三)的相关文章

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

直接上代码: # python2 # -*- coding: utf-8 -*- import urllib2 import re import string import os import shutil def crawl_taobaoMM(baseUrl, start, end): imgDir = 'mm_img' isImgDirExist = os.path.exists(imgDir) if not isImgDirExist: os.makedirs(imgDir) else:

python爬虫(三)--Python的set()

如果你已经掌握了爬虫基础,看了我前面三个基础再来继续看这一篇文章.这篇文章主要讲解爬虫程序中必须要用到的python集合,如果你对集合很了解.那可以不用看. 在爬虫程序中,为了不重复爬取已经爬过的页面,我们需要把已经爬过的页面的url放进集合中,在每一次要爬取某一个url之前,先看看集合里面是否已经存在,如果已经存在跳过这个url,如果不存在我们把ur放进聚合中,然后再去爬取这个页面 python提供了set这种数据结构,set是一种无序的,不包含重复元素的结构,一般用来测试是否已经包含了某元素

Python爬虫(三)_urllib2:get和post请求

urllib.urlencode() urllib和urllib2都是接受URL请求的相关参数,但是提供了不同的功能.两个最显著的不同如下: urllib仅可以接受URL,不能创建设置了headers的Request类实例: 但是urllib提供了urlencode方法用来GET查询字符串的产生,而urllib2则没有.(这是urllib和urllib2经常一起使用的主要原因) 编码工作使用urllib的urlencode()函数,帮我们将key:value这样的键值对转换成"key=value

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

文化         经管 ....略 结论: 一个模块的评分与评论数相关,评分为 [8.8——9.2] 之间的书籍评论数往往是模块中最多的 原文地址:https://www.cnblogs.com/LexMoon/p/douban3.html

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

决策树框架: 1 # coding=utf-8 2 import matplotlib.pyplot as plt 3 4 decisionNode = dict(boxstyle='sawtooth', fc='10') 5 leafNode = dict(boxstyle='round4', fc='0.8') 6 arrow_args = dict(arrowstyle='<-') 7 8 9 def plotNode(nodeTxt, centerPt, parentPt, nodeTy

Python爬虫进阶三之Scrapy框架安装配置

初级的爬虫我们利用urllib和urllib2库以及正则表达式就可以完成了,不过还有更加强大的工具,爬虫框架Scrapy,这安装过程也是煞费苦心哪,在此整理如下. Windows 平台: 我的系统是 Win7,首先,你要有Python,我用的是2.7.7版本,Python3相仿,只是一些源文件不同. 官网文档:http://doc.scrapy.org/en/latest/intro/install.html,最权威哒,下面是我的亲身体验过程. 1.安装Python 安装过程我就不多说啦,我的电

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

本文是博主原创随笔,转载时请注明出处Maple2cat|Python爬虫学习:三.爬虫的基本操作与流程 一般我们使用Python爬虫都是希望实现一套完整的功能,如下: 1.爬虫目标数据.信息: 2.将数据或信息存入数据库中: 3.数据展示,即在Web端进行显示,并有自己的分析说明. 这次我先介绍第一个功能中所需要实现的基本操作: 爬虫的基本操作:      表示必须步骤           表示可选步骤 导入爬虫所需要的库(如:urllib.urllib2.BeautifulSoup.Scrap

Python爬虫利器三之Xpath语法与lxml库的用法

前面我们介绍了 BeautifulSoup 的用法,这个已经是非常强大的库了,不过还有一些比较流行的解析库,例如 lxml,使用的是 Xpath 语法,同样是效率比较高的解析方法.如果大家对 BeautifulSoup 使用不太习惯的话,可以尝试下 Xpath. 参考文档: lxml python 官方文档 XPath语法参考 w3school 安装 pip install lxml 利用 pip 安装即可 XPath语法 XPath 是一门在 XML 文档中查找信息的语言.XPath 可用来在

Python网络爬虫(三)

AJAX学习 AJAX=Asynchronous JavaScript and XML(异步的 JavaScript 和 XML).通俗来说,AJAX是一种无需加载整个网页的情况下,通过在后台与服务器进行少量数据交换,更新部分网页的技术,用于创建快速动态网页的技术. 向服务器发送请求与服务器的响应 发送请求可以利用XMLHttpRequest对象的open()和send()方法. 方法 描述 open(method,url,async) 规定请求的类型.URL 以及是否异步处理请求.method

Python爬虫教程-25-数据提取-BeautifulSoup4(三)

Python爬虫教程-25-数据提取-BeautifulSoup4(三) 本篇介绍 BeautifulSoup 中的 css 选择器 css 选择器 使用 soup.select 返回一个列表 通过标签名称:soup.select("title") 通过类名:soup.select(".centent") id 查找:soup.select("#name_id") 组合查找:soup.select("div #input_content