前言
本节为大家带来一个最简单的Python爬虫项目,相信大家可以看懂的。从0到1的过程详细写出来,希望能帮助到大家
小说网站的基本结构
首页(总目录)→分类→小说目录页→小说各章节;
与网站的交互
通常都是用户通过浏览器(当IE)访问网站(网络上的服务器)。
浏览器:网址(href)、请求(requests)→网站服务器:响应(response)给浏览器→浏览器:缓存并呈现回复的内容。
添加第三方模块
第三方模块添加工具pip必须在安装python3.5时有勾选安装。
编辑或新建C:Userswwuhnwu01pippip.ini:
[global] respect-virtualenv = true download-cache = f:/Python/pip/cache log-file = f:/Python/pip/pip.log [install] timeout = 30 find-links = http://pypi.douban.com find-links = http://pypi.douban.com/simple
pycharm→文件→setting→project interpreter→pip→右边加号+→manage repositories→右边加号+→添加第三方模块的镜像服务器http://pypi.douban.com/和http://pypi.douban.com/simple
4 一个简单的网络爬虫
3.1 新建项目
3.2 设置项目编译器
基本的思路:
进入一个小说的目录页,请求到目录(包括各章节的href和章节标题)的内容,提取到全部的href,再通过各href请求到各网页的内容,经过数据清洗和适当的回到,写入到一个文本文件
代码:
import requests import re # 1 获取小说目录页 url = 'http://www.xiaoshuotxt.org/wuxia/1617/' response = requests.get(url) response.encoding = 'utf-8' html = response.text title = re.findall(r'<meta name="keywords" content="(.*?),',html)[0] # 4 数据持久化,写入txt) fb = open('%s.txt'%title, 'w', encoding='utf-8'); # 2 提取章节 menu = re.findall(r'正文(.*?)</table>',html)[0] chapter_info_list = re.findall(r'<a href="(.*?)" title=".*?">(.*?)</a>',menu) # 3 循环访问章节,并获取内容 for chapter_info in chapter_info_list: chapter_url = chapter_info[0] chapter_title = chapter_info[1] if 'http' not in chapter_url: chapter_url = 'http://www.xiaoshuotxt.org%s' % chapter_url chapter_response = requests.get(chapter_url) chapter_response.encoding = 'utf-8' chapter_html = chapter_response.text # 数据提取 chapter_content = re.findall(r'<div class="panel-body" id="htmlContent">(.*?)</div>',chapter_html) # 数据清洗(按页面规律) chapter_content = chapter_content.replace(' ','') chapter_content = chapter_content.replace('<br /><br /><br>','') # 数据持久化(写入txt),先要在前面新建文件 fb.write(chapter_title) fb.write(' ') fb.write(chapter_content) fb.write(' ') #用以下语句可以看到动态过程 print(chapter_url)
以上代码运行后,即可把整部小说的内容写入文本文件。
不同的网站,内面内容的写法会有差别,在提取数据和清洗数据时要做相应调整变化。
一些网站会禁止爬虫,当你尝试爬取网站资源时,一些网站会有反爬策略,将你的IP加入黑名单,当你爬取或访问时,页面会响应为:“HTTP Error 403: Forbidden错误”。
学习从来不是一个人的事情,要有个相互监督的伙伴,工作需要学习python或者有兴趣学习python的伙伴可以私信回复小编“学习” 领取全套免费python学习资料、视频()装包
部分素材来源于网络:侵删