一、什么是爬虫
爬虫:一段自动抓取互联网信息的程序,从互联网上抓取对于我们有价值的信息。
二、Python爬虫架构
Python 爬虫架构主要由五个部分组成,分别是调度器、URL管理器、网页下载器、网页解析器、应用程序(爬取的有价值数据)。 调度器:相当于一台电脑的CPU,主要负责调度URL管理器、下载器、解析器之间的协调工作。
URL管理器:包括待爬取的URL地址和已爬取的URL地址,防止重复抓取URL和循环抓取URL,实现URL管理器主要用三种方式,通过内存、数据库、缓存数据库来实现。
网页下载器:通过传入一个URL地址来下载网页,将网页转换成一个字符串,网页下载器有urllib2(Python官方基础模块)包括需要登录、代理、和cookie,requests(第三方包)
网页解析器:将一个网页字符串进行解析,可以按照我们的要求来提取出我们有用的信息,也可以根据DOM树的解析方式来解析。网页解析器有正则表达式(直观,将网页转成字符串通过模糊匹配的方式来提取有价值的信息,当文档比较复杂的时候,该方法提取数据的时候就会非常的困难)、html.parser(Python自带的)、beautifulsoup(第三方插件,可以使用Python自带的html.parser进行解析,也可以使用lxml进行解析,相对于其他几种来说要强大一些)、lxml(第三方插件,可以解析 xml 和 HTML),html.parser 和 beautifulsoup 以及 lxml 都是以 DOM 树的方式进行解析的。
应用程序:就是从网页中提取的有用数据组成的一个应用。
 

import urllib.request
import http.cookiejar url = "http://www.baidu.com"
response1 = urllib.request.urlopen(url)
print("第一种方法")
#获取状态码,200表示成功
print(response1.getcode())
#获取网页内容的长度
print(len(response1.read()))
第一种方法
200
156265
print("第二种方法")
request = urllib.request.Request(url)
#模拟Mozilla浏览器进行爬虫
request.add_header("user-agent","Mozilla/5.0")
response2 = urllib.request.urlopen(request)
print(response2.getcode())
print(len(response2.read()))
第二种方法
200
156328
print("第三种方法")
cookie = http.cookiejar.CookieJar()
#加入urllib.request处理cookie的能力
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie))
urllib.request.install_opener(opener)
response3 = urllib.request.urlopen(url)
print(response3.getcode())
print(len(response3.read()))
print(cookie)
第三种方法
200
156488
<CookieJar[<Cookie BAIDUID=CA8C47A224EE898DC34E66D0182C70C3:FG=1 for .baidu.com/>, <Cookie BIDUPSID=CA8C47A224EE898D968EF5993499742B for .baidu.com/>, <Cookie H_PS_PSSID=1446_21123 for .baidu.com/>, <Cookie PSTM=1575029972 for .baidu.com/>, <Cookie delPer=0 for .baidu.com/>, <Cookie BDSVRTM=0 for www.baidu.com/>, <Cookie BD_HOME=0 for www.baidu.com/>]>
四、第三方库 Beautiful Soup 的安装
Beautiful Soup: Python 的第三方插件用来提取 xml 和 HTML 中的数据,官网地址 https://www.crummy.com/software/BeautifulSoup/ 1、安装 Beautiful Soup
pip install bs4
2、测试是否安装成功

编写一个 Python 文件,输入:
import bs4
print(bs4)
<module 'bs4' from 'e:\\python\\lib\\site-packages\\bs4\\__init__.py'>
五、使用 Beautiful Soup 解析 html 文件
import re
from bs4 import BeautifulSoup html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
#创建一个BeautifulSoup解析对象
soup = BeautifulSoup(html_doc,"html.parser",from_encoding="utf-8")
#获取所有的链接
links = soup.find_all('a')
print("所有的链接")
for link in links:
print(link.name,link['href'],link.get_text())
所有的链接
a http://example.com/elsie Elsie
a http://example.com/lacie Lacie
a http://example.com/tillie Tillie
print("获取特定的URL地址")
link_node = soup.find('a',href="http://example.com/elsie")
print(link_node.name,link_node['href'],link_node['class'],link_node.get_text()) print("正则表达式匹配")
link_node = soup.find('a',href=re.compile(r"ti"))
print(link_node.name,link_node['href'],link_node['class'],link_node.get_text()) print("获取P段落的文字")
p_node = soup.find('p',class_='story')
print(p_node.name,p_node['class'],p_node.get_text())
获取特定的URL地址
a http://example.com/elsie ['sister'] Elsie
正则表达式匹配
a http://example.com/tillie ['sister'] Tillie
获取P段落的文字
p ['story'] Once upon a time there were three little sisters; and their names were
Elsie,
Lacie and
Tillie;
and they lived at the bottom of a well.

吴裕雄--python学习笔记:爬虫基础的更多相关文章

  1. 吴裕雄--python学习笔记:爬虫包的更换

    python 3.x报错:No module named 'cookielib'或No module named 'urllib2' 1. ModuleNotFoundError: No module ...

  2. 吴裕雄--python学习笔记:爬虫

    import chardet import urllib.request page = urllib.request.urlopen('http://photo.sina.com.cn/') #打开网 ...

  3. 吴裕雄--python学习笔记:sqlite3 模块

    1 sqlite3.connect(database [,timeout ,other optional arguments]) 该 API 打开一个到 SQLite 数据库文件 database 的 ...

  4. 吴裕雄--python学习笔记:os模块函数

    os.sep:取代操作系统特定的路径分隔符 os.name:指示你正在使用的工作平台.比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'. os.getcwd:得 ...

  5. 吴裕雄--python学习笔记:os模块的使用

    在自动化测试中,经常需要查找操作文件,比如说查找配置文件(从而读取配置文件的信息),查找测试报告(从而发送测试报告邮件),经常要对大量文件和大量路径进行操作,这就依赖于os模块. 1.当前路径及路径下 ...

  6. 吴裕雄--python学习笔记:BeautifulSoup模块

    import re import requests from bs4 import BeautifulSoup req_obj = requests.get('https://www.baidu.co ...

  7. 吴裕雄--python学习笔记:通过sqlite3 进行文字界面学生管理

    import sqlite3 conn = sqlite3.connect('E:\\student.db') print("Opened database successfully&quo ...

  8. 吴裕雄--python学习笔记:sqlite3 模块的使用与学生信息管理系统

    import sqlite3 cx = sqlite3.connect('E:\\student3.db') cx.execute( '''CREATE TABLE StudentTable( ID ...

  9. Python学习笔记之基础篇(-)python介绍与安装

    Python学习笔记之基础篇(-)初识python Python的理念:崇尚优美.清晰.简单,是一个优秀并广泛使用的语言. python的历史: 1989年,为了打发圣诞节假期,作者Guido开始写P ...

随机推荐

  1. springboot +Thymeleaf+UEditor整合记录

    1,ueditor官网下载:https://ueditor.baidu.com/website/download.html  下载相应的工具包和源码,ps:源码放到工程中 2,解压放到放到项目中,sp ...

  2. 干货|Kubernetes集群部署
Nginx-ingress Controller

    Kubernetes提供了两种内建的云端负载均衡机制用于发布公共应用,一种是工作于传输层的Service资源,它实现的是TCP负载均衡器:另一种是Ingress资源,它实现的是HTTP(S)负载均衡器 ...

  3. 66)vector基础总结

    基本知识: 1)vector 样子  其实就是一个动态数组: 2)vector的基本操作: 3)vector对象的默认构造 对于类  添加到  容器中  要有  拷贝构造函数---> 这个注意 ...

  4. JS面向对象,原型,继承

    ECMAScript有两种开发模式:1.函数式(过程化),2.面向对象(OOP).面向对象的语言有一个标志,那就是类的概念,而通过类可以创建任意多个具有相同属性和方法的对象.但是,ECMAScript ...

  5. NOIP复赛文件路径怎么写

    以2018年NOIP普及组复赛为例,四道题对应着四个文件夹:   随便选一道题,比如第一道题,进入title目录,可以看到title1.in, title1.ans, title2.in, title ...

  6. 蓝桥杯 K好数(dp)

    Description 如果一个自然数N的K进制表示中任意的相邻的两位都不是相邻的数字,那么我们就说这个数是K好数.求L位K进制数中K好数的数目.例如K = 4,L = 2的时候,所有K好数为11.1 ...

  7. 翻译——1_Project Overview, Data Wrangling and Exploratory Analysis-checkpoint

    为提高提高大学能源效率进行建筑能源需求预测 本文翻译哈佛大学的能源分析和预测报告,这是原文 暂无数据源,个人认为学习分析方法就足够 内容: 项目概述 了解数据 探索性分析 使用不同的机器学习方法进行预 ...

  8. day50-线程-定时器

    #1.定时器: from threading import Timer def func(): print('定时器') t = Timer(1,func) #定时一秒,开启func线程. t.sta ...

  9. spark安装和使用

    local模式 概述 local模式就是在一台计算机上运行spark程序,通常用于在本机上练手和测试,它将线程映射为worker. 1)local: 所有计算都运行在一个线程当中,没有任何并行计算,通 ...

  10. GIS开源库OpenSceneGraph(OSG)、OSGEarth、GDAL、Qt、CGAL、Boost

    GIS开源有这些库:OpenSceneGraph(OSG).OSGEarth.GDAL.Qt.CGAL.Boost