您的位置:首页 > 编程语言 > Python开发

用Python做的爬取“笔趣阁”的小说简单爬虫(校花的贴身高手为例)

2019-03-04 19:47 447 查看

用Python做的爬取“笔趣阁”的小说简单爬虫

  • 话不多说先上代码,备注都在代码内
#导入所需要用的包
import requests
from lxml import etree

# 爬取网页中的网址和标题
def title_info(url,headers):
#发送请求
response = requests.get(url=url,headers=headers)
html = response.text
#使用Xpath方式匹配到所需的内容
count = etree.HTML(html)
#获取每个标题
title = count.xpath('//a[@style]/text()')
#获取url地址
href = count.xpath('//dd/a/@href')
get_info(title,href,url)

# 获取文章
def get_info(title,href,url):
for_num = 0
#文章页数为所有标题的个数
page = len(title)
#去掉无用的href链接
href.remove('/0_671/4962666.html')
#循环链接
for nums in href:
for_num += 1
# 获取href链接的长度
numss = len(nums)
#如果长度大于正常长度
#一般有两种长度
#    4972271.html
#    /0_671/4972271.html
#两者不一样,拼接的url地址也不同
#判断是否大于正常长度,如果不是那就重新赋值url
if numss > 12:
url = 'https://www.xs.la'
#进行拼接
url1 = url + nums
#发送请求
response = requests.get(url=url1, headers=headers)
html = response.text
count = etree.HTML(html)
#拿到内容
article = count.xpath('//div[@id="content"]/text()')

info_article = ""   # 定义一个空字符串,接收内容
nums = 0
# 循环出小说的内容
for i in article:
article_long = len(article)  # 小说的长度
nums += 1
i2 = "\n" + i    #用字符串拼接的方式,'\n'是换行的意思
info_article += i2   #再拼接(与上面一步可以拼在一起)
#如果循环次数等于小说长度 写入小说
if nums == article_long:
print("正在下载第{}章".format(page))
with open("./校花的贴身高手/第{}章.txt".format(page),'w+',encoding="utf-8") as f:
f.write(info_article)
print("第{}章下载完成".format(page))
page -= 1

if __name__ == '__main__':
url = "https://www.xs.la/0_671/"     #小说目录网址
headers = {
"User - Agent": "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 72.0.3626.119Safari / 537.36"
}       #次数多了可能会被封,所以要使用代理IP
title_info(url,headers)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: