Python网络爬虫实战入门
一、网络爬虫
网络爬虫(又被称为网页蜘蛛,网络机器人),是一种按照一定的规则,自动地抓取万维网信息的程序。
爬虫的基本流程:
- 发起请求:
通过HTTP库向目标站点发起请求,也就是发送一个Request,请求可以包含额外的header等信息,等待服务器响应
- 获取响应内容:
如果服务器能正常响应,会得到一个Response,Response的内容便是所要获取的页面内容,类型可能是HTML,Json字符串,二进制数据(图片或者视频)等类型
- 解析内容:
得到的内容可能是HTML,可以用正则表达式,页面解析库进行解析,可能是Json,可以直接转换为Json对象解析,可能是二进制数据,可以做保存或者进一步的处理
- 保存数据:
保存形式多样,可以存为文本,也可以保存到数据库,或者保存特定格式的文件
二、准备
准备安装以下三个库:
1、urllib库
Urllib是python内置的标准库模块,使用它可以像访问本地文本文件一样读取网页的内容。Python的Urllib库模块包括以下四个模块:
urllib.request 请求模块
urllib.error 异常处理模块
urllib.parse url解析模块
urllib.robotparser解析模块
2、urllib.request模块的常用方法
基本使用步骤:
(1)导入urllib.request模块
from urllib import request
(2)连接要访问的网站,发起请求
resp = request.urlopen("http://网站IP地址")
(3)获取网站代码信息
print(resp.read().decode())
3、BeautifulSoup模块
(1)BeautifulSoup模块的基本元素
(2)标签树
在解析网页文档的过程中,需要应用BeautifulSoup模块对HTML内容进行遍历。
设有如下的一个HTML文档:
<html>
<head>
....
</head>
<body>
<p class="title"> The demo Python Project.</p>
<p class="course"> Python is a programming language.
<a href="http://www.icourse163.com"> Basic Python </a>
<a href="http:..www.python.org"> Advanced Python </a>
</p>
</body>
</html>
(3)BeautifulSoup模块对象“标签树”的上行遍历属性
(4)BeautifulSoup模块对象“标签树”的下行遍历属性
(5)BeautifulSoup模块对象的信息提取方法
三、入门练习
1、抓取湖北师范大学网站基本信息
import urllib.request
response=urllib.request.urlopen("http://www.hbnu.edu.cn/")
print(response.info())
print('\n*************************************************************\n')
print(response.getcode())
print('\n*************************************************************\n')
print(response.read())
2、爬取最好大学网站的大学排名榜
import bs4
from urllib import request
from bs4 import BeautifulSoup
def getHTMLText(url):
'''获取页面'''
try:
resp = request.urlopen(url)
html_data = resp.read().decode('utf-8')
return html_data
except:
return ""
def fillUnivList(ulist, html):
'''处理页面'''
soup = BeautifulSoup(html, "html.parser")
for tr in soup.find('tbody').children: # 找到关键词'tbody'后,搜索'td'子项
if isinstance(tr, bs4.element.Tag):
tds = tr('td')
ulist.append([tds[0].string, tds[1].string, tds[3].string])
def printUnivList(ulist, num):
'''格式输出页面'''
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print(tplt.format("排名", "学校名称", "学校类型", chr(12288)))
for i in range(num):
u = ulist[i]
print(tplt.format(u[0], u[1], u[2], chr(12288)))
if __name__ == '__main__':
uinfo = []
url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2020.html' # 2020年
html = getHTMLText(url)
fillUnivList(uinfo, html)
printUnivList(uinfo, 20) # 输出20个大学排名
3、爬取网络版小说《红楼梦》
爬取某网站的网络版小说《红楼梦》。打开《红楼梦》小说的目录页面会如图所示。
运用F12,找对应章节的位置
首先爬取对应章节的网址:
from urllib import request
from bs4 import BeautifulSoup
if __name__ == '__main__':
# 目录页
url = 'http://www.136book.com/hongloumeng/'
head = {}
head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'
req = request.Request(url, headers = head)
response = request.urlopen(req)
html = response.read()
# 解析目录页
soup = BeautifulSoup(html, 'lxml')
# find_next找到第二个<div>
soup_texts = soup.find('div', id = 'book_detail', class_= 'box1').find_next('div')
# 遍历ol的子节点,打印出章节标题和对应的链接地址
for link in soup_texts.ol.children:
if link != '\n':
print(link.text + ': ', link.a.get('href'))
爬取每一章节的内容:
from urllib import request
from bs4 import BeautifulSoup
if __name__ == '__main__':
# 第1章的网址
url = 'http://www.136book.com/hongloumeng/qlxecbzt/'
head = {}
# 使用代理
#head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'
req = request.Request(url, headers = head)
response = request.urlopen(req)
html = response.read()
# 创建request对象
soup = BeautifulSoup(html, 'lxml')
# 找出div中的内容
soup_text = soup.find('div', id = 'content')
# 输出其中的文本
print(soup_text.text)
当然如此显示会很不好看,我们去试一下生成一本《红楼梦》.txt,默认存在我的D盘
from urllib import request
from bs4 import BeautifulSoup
if __name__ == '__main__':
url = 'http://www.136book.com/hongloumeng/'
head = {}
req = request.Request(url, headers = head)
response = request.urlopen(req)
html = response.read()
soup = BeautifulSoup(html, 'lxml')
soup_texts = soup.find('div', id = 'book_detail', class_= 'box1').find_next('div')
# 打开文件
f = open('D:\hongloumeng.txt','w')
# 循环解析链接地址
for link in soup_texts.ol.children:
if link != '\n':
download_url = link.a.get('href')
download_req = request.Request(download_url, headers = head)
download_response = request.urlopen(download_req)
download_html = download_response.read()
download_soup = BeautifulSoup(download_html, 'lxml')
download_soup_texts = download_soup.find('div', id = 'content')
# 抓取其中文本
download_soup_texts = download_soup_texts.text
# 写入章节标题
f.write(link.text + '\n\n')
# 写入章节内容
f.write(download_soup_texts)
f.write('\n\n')
f.close()
感悟:效果很不错,以后看小说不愁没资源了,自行爬取txt导入手机免费看(也可以复制粘贴到word自动分行),当然之前还在52pj看过爬妹子图,乐趣无穷。
Python网络爬虫实战入门的更多相关文章
- 关于Python网络爬虫实战笔记③
Python网络爬虫实战笔记③如何下载韩寒博客文章 Python网络爬虫实战笔记③如何下载韩寒博客文章 target:下载全部的文章 1. 博客列表页面规则 也就是, http://blog.sina ...
- python网络爬虫实战PDF高清完整版免费下载|百度云盘|Python基础教程免费电子书
点击获取提取码:vg1y python网络爬虫实战帮助读者学习Python并开发出符合自己要求的网络爬虫.网络爬虫,又被称为网页蜘蛛,网络机器人,是一种按照一定的规则,自动地抓取互联网信息的程序或者脚 ...
- Python网络爬虫实战(一)快速入门
本系列从零开始阐述如何编写Python网络爬虫,以及网络爬虫中容易遇到的问题,比如具有反爬,加密的网站,还有爬虫拿不到数据,以及登录验证等问题,会伴随大量网站的爬虫实战来进行. 我们编写网络爬虫最主要 ...
- python网络爬虫实战之快速入门
本系列从零开始阐述如何编写Python网络爬虫,以及网络爬虫中容易遇到的问题,比如具有反爬,加密的网站,还有爬虫拿不到数据,以及登录验证等问题,会伴随大量网站的爬虫实战来进行. 我们编写网络爬虫最主要 ...
- 关于Python网络爬虫实战笔记①
python网络爬虫项目实战笔记①如何下载韩寒的博客文章 python网络爬虫项目实战笔记①如何下载韩寒的博客文章 1. 打开韩寒博客列表页面 http://blog.sina.com.cn/s/ar ...
- python网络爬虫之入门[一]
目录 前言 一.探讨什么是python网络爬虫? 二.一个针对于网络传输的抓包工具fiddler 三.学习request模块来爬取第一个网页 * 扩展内容(爬取top250的网页) 后记 @(目录) ...
- Python网络爬虫实战:根据天猫胸罩销售数据分析中国女性胸部大小分布
本文实现一个非常有趣的项目,这个项目是关于胸罩销售数据分析的.是网络爬虫和数据分析的综合应用项目.本项目会从天猫抓取胸罩销售数据,并将这些数据保存到SQLite数据库中,然后对数据进行清洗,最后通过S ...
- Python 网络爬虫 002 (入门) 爬取一个网站之前,要了解的知识
网站站点的背景调研 1. 检查 robots.txt 网站都会定义robots.txt 文件,这个文件就是给 网络爬虫 来了解爬取该网站时存在哪些限制.当然了,这个限制仅仅只是一个建议,你可以遵守,也 ...
- Python网络爬虫实战(三)照片定位与B站弹幕
之前两篇已经说完了如何爬取网页以及如何解析其中的数据,那么今天我们就可以开始第一次实战了. 这篇实战包含两个内容. * 利用爬虫调用Api来解析照片的拍摄位置 * 利用爬虫爬取Bilibili视频中的 ...
随机推荐
- Sonarqube C# 配置资料整理
c#配置方式: http://www.cnblogs.com/CoderAyu/p/9416376.html http://www.cnblogs.com/jingridong/p/6513884.h ...
- symfony2已有数据表导入实体时报错 Doctrine does not support reverse engineering from tables that don't have a primary key
先在配置文件 app/config/config.yml中配置 schema_filter: /^(?!(tablename))/ 即可,或者在出现问题表都加上一个id 然后再使用命令 php app ...
- 停止:service jenkins stop,提示:Failed to stop jenkins.service: Unit jenkins.service not loaded.
uni@uni-virtual-machine:~$ service jenkins stop Failed to stop jenkins.service: Unit jenkins.service ...
- Python实现Telnet连接
import loggingimport telnetlibimport timeclass TelnetClient(): def __init__(self,): self.tn = telnet ...
- 10分钟教你使用Picgo+GitHub+ jsDelivr搭建CDN加速免费图床
前言 经常写Markdown或者博客的同学,肯定都要用到图床.图床是什么呢?其实相当于一个存储图片的网站,类似百度云这样,不过上传图片到图床后可以直接通过外链进行访问. 比如把本地一张a.jpg上传到 ...
- 鸿蒙内核源码分析(系统调用篇) | 开发者永远的口头禅 | 百篇博客分析OpenHarmony源码 | v37.03
百篇博客系列篇.本篇为: v37.xx 鸿蒙内核源码分析(系统调用篇) | 开发者永远的口头禅 | 51.c.h .o 任务管理相关篇为: v03.xx 鸿蒙内核源码分析(时钟任务篇) | 触发调度谁 ...
- P4544 [USACO10NOV]Buying Feed G
part 1 暴力 不难发现有一个 $\mathcal O(K^2n)$ 的基础 dp: $$f_{i,j+l}=\min(f_{i,j+l},f_{i-1,j}+(x_i-x_{i-1})\time ...
- Bert文本分类实践(二):魔改Bert,融合TextCNN的新思路
写在前面 文本分类是nlp中一个非常重要的任务,也是非常适合入坑nlp的第一个完整项目.虽然文本分类看似简单,但里面的门道好多好多,博主水平有限,只能将平时用到的方法和trick在此做个记录和分享 ...
- .NET Core 基于Quartz的UI可视化操作组件 GZY.Quartz.MUI 简介
前言 最近在用Quartz做定时任务.虽然很方便,但是Quartz自己貌似是没有UI界面的..感觉操作起来 就很难受.. 查了一下,貌似有个UI组件 不过看了一下文档..直接给我劝退了..太麻烦了 我 ...
- 3DGIS开发使用的开源项目
gdal proj4 vcglib assimp libjpg libpng osg libtess2 cesiumjs glm