Python制作爬虫采集小说

yipeiwu_com6年前Python爬虫

开发工具:python3.4
操作系统:win8
主要功能:去指定小说网页爬小说目录,按章节保存到本地,并将爬过的网页保存到本地配置文件。
被爬网站:http://www.cishuge.com/
小说名称:灵棺夜行
代码出处:本人亲自码的

import urllib.request
import http.cookiejar

import socket
import time
import re

timeout = 20
socket.setdefaulttimeout(timeout)

sleep_download_time = 10
time.sleep(sleep_download_time)
 
def makeMyOpener(head = {
 'Connection': 'Keep-Alive',
 'Accept': 'text/html, application/xhtml+xml, */*',
 'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'
}):
 cj = http.cookiejar.CookieJar()
 opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
 header = []
 for key, value in head.items():
  elem = (key, value)
  header.append(elem)
 opener.addheaders = header
 return opener
 
def saveFile(save_path,txts):
 f_obj = open(save_path,'w+')
 for item in txts:
  f_obj.write(item+'\n')
 f_obj.close()
 
#get_code_list
code_list='http://www.cishuge.com/read/0/771/'
oper = makeMyOpener()
uop = oper.open(code_list,timeout=1000)
data = uop.read().decode('gbk','ignore')

pattern = re.compile('<li><a href="(.*?)".*?>(.*?)</a></li>',re.S)

items = re.findall(pattern,data)

print ('获取列表完成')
url_path='url_file.txt'

url_r=open(url_path,'r')
url_arr=url_r.readlines(100000)
url_r.close()
print (len(url_arr))

url_file=open(url_path,'a')

print ('获取已下载网址')

for tmp in items:
 save_path = tmp[1].replace(' ','')+'.txt'
 url = code_list+tmp[0]
 if url+'\n' in url_arr:
  continue
 print('写日志:'+url+'\n')
 url_file.write(url+'\n')
 opene = makeMyOpener()
 op1 = opene.open(url,timeout=1000)
 data = op1.read().decode('gbk','ignore')
 opene.close()
 pattern = re.compile('    (.*?)<br />',re.S)
 txts = re.findall(pattern,data)
 saveFile(save_path,txts)
 
url_file.close()

虽然代码还是有点瑕疵,还是分享给大家,一起改进

相关文章

使用BeautifulSoup爬虫程序获取百度搜索结果的标题和url示例

熟悉Java的jsoup包的话,对于Python的BeautifulSoup库应该很容易上手。 复制代码 代码如下:#coding: utf-8import sysimport urll...

Python 多线程抓取图片效率对比

目的: 是学习python 多线程的工作原理,及通过抓取400张图片这种IO密集型应用来查看多线程效率对比 import requests import urlparse imp...

Python抓取框架 Scrapy的架构

Python抓取框架 Scrapy的架构

最近在学Python,同时也在学如何使用python抓取数据,于是就被我发现了这个非常受欢迎的Python抓取框架Scrapy,下面一起学习下Scrapy的架构,便于更好的使用这个工具。...

Python爬虫实现爬取百度百科词条功能实例

Python爬虫实现爬取百度百科词条功能实例

本文实例讲述了Python爬虫实现爬取百度百科词条功能。分享给大家供大家参考,具体如下: 爬虫是一个自动提取网页的程序,它为搜索引擎从万维网上下载网页,是搜索引擎的重要组成。爬虫从一个或...

Scrapy-redis爬虫分布式爬取的分析和实现

Scrapy-redis爬虫分布式爬取的分析和实现

Scrapy Scrapy是一个比较好用的Python爬虫框架,你只需要编写几个组件就可以实现网页数据的爬取。但是当我们要爬取的页面非常多的时候,单个主机的处理能力就不能满足我们的需求了...