python 爬虫

一、支持任意章节链接或目录链接

# -*- coding: utf-8 -*-
"""
Created on Thu Jan  6 12:38:42 2022

@author: shiyu
"""

import time
import requests
from lxml import etree
import re

def spider(url):
    html=requests.get(url,headers=headers)
    html_=etree.HTML(html.text)
    words=html_.xpath('//div[@id="content"]/text()')
    
    k=r'(<title>)(.*?)(</title>)'
    title=re.search(k,html.text)
    
    with open('{}.txt'.format(title2[0]),'a',encoding='utf-8') as f:
        f.write(title.group(2)+'\n')
        for line in words:
            line=line.replace('\\xa0',' ')
            f.write(line+'\n')
        f.write('\n')

headers={'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,\
         like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62'
    }
#替换这里的url
url='https://www.81zw.com/book/69283/'
url_='https://www.81zw.com{}'
if url.find('html')!=-1:
    request=requests.get(url,headers=headers)
    k=r'(&larr; <a href=")(.*?)(">章节目录</a>)'
    link_content=re.search(k,request.text).group(2)
    content_url=url_.format(link_content)
    html_=requests.get(content_url,headers=headers)
else:
    html_=requests.get(url,headers=headers)
html=etree.HTML(html_.text)
links=html.xpath('//dd/a/@href')
title2=html.xpath('//meta[@property="og:title"]/@content')

with open('{}.txt'.format(title2[0]),'w',encoding='utf-8') as f:
    pass

for pos,link in enumerate(links):
    url_con=url_.format(link)
    spider(url_con)
    time.sleep(0.1)
    print('第'+str(pos+1)+'章')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值