码迷,mamicode.com
首页 > 其他好文 > 详细

【爬虫】biqukan抓取2.0版

时间:2019-03-15 17:30:42      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:2.0   sleep   python3   head   进度   换行   status   pytho   ext   

#!python3.7
import requests,sys,time,logging,random
from lxml import etree
logging.basicConfig(level=logging.ERROR, format= %(asctime)s - %(levelname)s: %(message)s) #DEBUG ERROR format显示格式可按自己喜好调整

#logging.disable(logging.CRITICAL) #调试日志是否显示开关
logging.debug(程序现在开始!) #调试日志开始标记
‘‘‘
时间:2019.3.15
功能:实现www.biqukan.com/1_1094/5403177.html小说下载为txt
版本:2.0
新增:加入了页面没有返回200成功码,异常处理;2.3功能合并;调试日志;
‘‘‘
global headers
headers={
    User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
    }

##0.获取所有章节url
def get_url_list(catalog_url):
    res=requests.get(catalog_url,headers=headers)
    
    if res.status_code==200:
        text=res.text
        html=etree.HTML(text)
        hrefs=html.xpath(//div[@class="listmain"]/dl/dt[2]/following-sibling::*/a/@href)

        #logging.debug(‘0.获取到的章节列表是:‘,hrefs) #【调试0】
        return hrefs
    raise Exception(页面没有正确返回哦!+res.text) #【调试】如果没有返回200则按错误抛出返回的状态码

##1.获取页面
def get_one_page(url):
    
    res=requests.get(url,headers=headers)
    if res.status_code==200:
        return res.text
    else:
        while res.status_code!=200:
            print(页面没有正确返回,正在重试请稍等哦!+res.text)
            res=requests.get(url,headers=headers)
            time.sleep(random.randint(1, 5))
        return res.text

##2.解析页面 3.写入txt文件
def parse_one_page(text):
    html=etree.HTML(text)
    title=html.xpath(//div[@class="content"]/h1//text())
    content=html.xpath(//div[@class="showtxt"]//text()) #去掉换行
    contents=‘‘.join(content).replace(\xa0*8,\n*2)#把列表转换为一整段文本,并把8个空格换为2个换行

    #logging.debug(‘2.解析到的标题是:‘,title)#【调试2】
    #logging.debug(‘2.解析到的内容是:‘,contents)
    
    #写入文件
    with open(一念永恒.txt,a,encoding=utf-8)as f:
        f.write(title[0]+\n+contents+\n)
                    
##主函数
def main():
    #0.获取章节列表的网址
    catalog_url=https://www.biqukan.com/1_1094/
    urls=get_url_list(catalog_url)
    
    #把网址传入详情抓取页面,并保存
    for i in range(len(urls)):
        rel_url=https://www.biqukan.com+urls[i]
        #1.获取一个页面text
        text=get_one_page(rel_url)
        #2.解析3.写入文件
        parse_one_page(text) 
        
        #显示下载进度
        sys.stdout.write("  已下载:%.3f%%" %  float(i/len(urls)) + \n)
        sys.stdout.flush() 

##执行入口    
if __name__==__main__:
    main()

 

【爬虫】biqukan抓取2.0版

标签:2.0   sleep   python3   head   进度   换行   status   pytho   ext   

原文地址:https://www.cnblogs.com/chenxi188/p/10538221.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!