Python笔记——第一个python爬虫

经过一天的学习, 终于写出了自己的第一个完整的爬虫, 虽然还是有一些瑕疵, 先放上代码, 后期再进行整理说明和更新。

代码很简单,用来爬取小说站点的一本小说并分章节进行保存。
== 首次更新:2020年2月5日 零点十八分 ==

#此代码用于实验爬虫爬取小说站点小说


import requests
import re
import time
import os


def get_section_list(get_url):           #获取书籍章节列表函数
    response=requests.get(get_url)
    response.encoding='gbk'
    html=response.text
    #以下三行注释掉的代码因为页面结构的原因,所以写了三个结构, 后面解释。
    #zhangjie0=re.findall('<a  title=".*?href="(.*?)">.*?-->\r\n            (.*?)</a>',html,re.S)   #0-4-8

    #zhangjie1 = re.findall(' /><a href="(.*?)".*?title=".*?">(.*?)</a>', html, re.S)       #1-5-9
    #zhangjie2 = re.findall('/><a  href="http://(.*?)" title=".*?>(.*?)</a>  </div>', html, re.S)    #2-6-10

    zhangjie3 = re.findall('<a  href="/(.*?)" title=".*?-->\r\n              (.*?)</a>  </li>', html, re.S) #3-7-11
    #return zhangjie0,zhangjie1,zhangjie2,zhangjie3
    return zhangjie3

book_url='http://www.kuuhu.com/xiaoshuo/288/288042/index.html'
section_list=get_section_list(book_url)          #获取列表


#--------------内容函数
def get_content(url,name):
    content_res = requests.get(url)
    content_res.encoding = 'gbk'
    html = content_res.text
    title = re.findall('<h1>(.*?)</h1>', html, re.S)
    content = re.findall('&nbsp;&nbsp;&nbsp;&nbsp;(.*?)<br />', html, re.S)

    path1="d:/book_download/"+name+".txt"     #以章节名命名文件名

    f = open(path1, "a")                #创建文件,并写入章节内容
    f.write(title[0] + "\n\n")
    for i in content:
        f.write(i + "\n")
    f.close()
#内容函数结束

f=open("d:/book/mulu.txt","a")

for i in section_list:
    a=i[1]
    b=a.replace('?','')
    #print(b)
    get_content('http://www.kuuhu.com/'+i[0],b)
    time.sleep(2)
    #f.write(i[0]+"\n")
    #f.write(i[1]+"\n")
    print(i[0])
    print(i[1])
  • 爬取的结果:
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值