1.python爬取笔趣阁小说
前一阵无聊想学习python,就有了以下代码,选取了笔趣阁这个大众化的网站,百度发现以笔趣阁为名的小说网站很多,本段代码只在百度结果里选取前五条,并选取了三个叫笔趣阁的网站,前五条里包含笔趣阁的任意一个网址就开始爬取。
from selenium import webdriver
import time
import re
import requests
from urllib.parse import urlparse
from lxml import etree
import random
header = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
}#使用selenium在百度自动搜索小说
def selenium_main(story):# 声明option = webdriver.ChromeOptions();# chrome正受到自动测试软件的控制对应option.add_experimental_option("excludeSwitches", ['enable-automation']);driver = webdriver.Chrome(options=option);# 打开百度driver.get('http://www.baidu.com');# 输入搜做关键字driver.find_element_by_id("kw").send_keys(story);# 点击百度一下按钮driver.find_element_by_id("su").click();# 休眠一下time.sleep(2);# 打开百度搜到的地址open_url(driver,story);# 在百度一览里,找到笔趣阁的网站,并打开
def open_url(driver,story):# 在百度一览里的前5条里,搜寻笔趣阁的小说网址# 初期化1indexStr = "1";# 初期化falseflag = False;for index in range(1, 6):# int转字符串indexStr = str(index);# 从id=1开始到id=5,获取a标签的内容title = driver.find_element_by_id(indexStr).find_element_by_tag_name("a").text# 查找标题里包含笔趣阁字样的第一条数据,退出循环if title.find("笔趣阁", 0, len(title)) != -1:print(title);flag = True;break;# 如果在一览里没有找到包含笔趣阁的标题,返回9if not flag and indexStr == "1":return "9";# 点击标题里包含笔趣阁文字的链接driver.find_element_by_id(indexStr).find_element_by_tag_name("a").click();# 取得所有窗口的handleshandles = driver.window_handles;# 切换到新打开的tab页里driver.switch_to.window(handles[-1]);# 休眠time.sleep(2);# 取得当前tab网页的urlcurrentUrl = driver.current_url;# http://www.biquge.info/47_47063/# https://www.biqumo.com/2_2730/# http://www.xbiquge.la/45/45587/print(currentUrl);# 判断是哪个url并调用爬虫switch_url(currentUrl,driver,story);# if res is not None:# if res.group() == "http://www.biquge.info":# biquge.spider_biquge_story(url)# elif res.group() == "http://www.xbiquge.la":# xinbiquge.spider_biquge_story(url)# else:# print("没有检索到")# else:# driver.switch_to.window(handles[0])# return flagdriver.quit()# http://www.biquge.info/47_47063/
# https://www.biqumo.com/2_2730/
# http://www.xbiquge.la/45/45587/
# 判断是哪个url并调用
def switch_url(currentUrl,driver,story):# [a-zA-z]+://[^\s]*# 匹配上记三个网址res = re.match("[a-zA-z]+://.*?[biquge|xbiquge|biqumo].*", currentUrl, re.I);# print(res)# print("res.group()------:" + res.group())try:# 如果是三个网站之一,执行if语句if res is not None:# 取得各自网站的关键字reContent = re.search(".*?(biquge|xbiquge|biqumo).*",res.group(),re.I);print("reContent:-------------:"+reContent.group(1))reContentStr = reContent.group(1);if "biquge"== reContentStr:# biquge# 开始调用爬取spider_story(currentUrl,1,story);elif "xbiquge" == reContentStr:# xbiquge# 开始调用爬取spider_story(currentUrl,2,story);else:# biqumo# 开始调用爬取spider_story(currentUrl,3,story);else:return "9";except:print("正则表达式判断出错!");driver.quit();return "9";def spider_story(currenturl,num,story):#根网址base_url = '%s' % currenturl;try:# 取得整个页面htmlhtml_str = spider_url(base_url, header);#print(html_str);# //*[@id="list"]/dl/dd[1]/a# 拿到html_str后就可以使用etree.HTML()方法获取html对象,之后就可以使用xpath方法了html = etree.HTML(html_str) # <Element html at 0x7ff3fe0d6108>old_url = base_url;sub_header = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36','Referer': '%s' % old_url}if 1 == num:# biqugeurl_list_1_2 = html.xpath('//*[@id="list"]/dl/dd[*]/a');for obj in url_list_1_2:# /2_2730/6967027.html----第1221章 大结局print(obj.attrib['href']+'----'+obj.text);new_url = base_url + obj.attrib['href']# 爬取文章内容responseText = spider_url(new_url, header);#//*[@id="content"]/text()sub_html = etree.HTML(responseText)# 提取文章的内容contents = sub_html.xpath('//*[@id="content"]/text()')# print("contents: "+contents);# 写入文件标题write_txt(story + ".txt", obj.text);for story_line in contents:# 写入文件每行的内容write_txt(story + ".txt", story_line);old_url = new_url# 模拟用户浏览,设置一个爬虫间隔,防止ip被封time.sleep(random.random() * 5)elif 2 == num:# xbiqugeurl_list_1_2 = html.xpath('//*[@id="list"]/dl/dd[*]/a');for obj in url_list_1_2:# print(obj.attrib['href'] + '----' + obj.text);parsed = urlparse(base_url);scheme = parsed.scheme;# 取得根网址:www.biqumo.comnetloc = parsed.netloc;# print(scheme+"=============="+netloc);# url做成new_url = scheme + "://" + netloc + obj.attrib['href']# 爬取文章内容responseText = spider_url(new_url, header);# //*[@id="content"]/text()sub_html = etree.HTML(responseText)# 提取文章的内容contents = sub_html.xpath('//*[@id="content"]/text()')print("title : "+obj.text);# 写入文件标题write_txt(story + ".txt", obj.text);for story_line in contents:# 写入文件每行的内容write_txt(story + ".txt", story_line);old_url = new_url# 模拟用户浏览,设置一个爬虫间隔,防止ip被封time.sleep(random.random() * 5)else:# biqumo /html/body/div[5]/dl/dd[13]/aurl_list_3 = html.xpath("/html/body/div[@class='listmain']/dl/dd[*]/a");parsed = urlparse(base_url);scheme = parsed.scheme;#取得根网址:www.biqumo.comnetloc = parsed.netloc;#print(scheme+"=============="+netloc);counter = 1;for obj in url_list_3:# /2_2730/6967027.html----第1221章 大结局# print(obj.attrib['href']+'----'+obj.text);new_url = scheme +"://"+netloc + obj.attrib['href']# 爬取文章内容responseText = spider_url(new_url, header);#//*[@id="content"]/text()sub_html = etree.HTML(responseText)# 提取文章的内容contents = sub_html.xpath('//*[@id="content"]/text()')# print("contents: "+contents);# 前12条是最新章节,pass掉if counter > 12:# 写入文件标题write_txt(story + ".txt", obj.text);for story_line in contents:# 写入文件每行的内容write_txt(story + ".txt", story_line);counter += 1;old_url = new_url# 模拟用户浏览,设置一个爬虫间隔,防止ip被封time.sleep(random.random() * 5)except Exception as e:print('爬取失败',e);#取得整个页面html
def spider_url(base_url,header):response = requests.get(base_url,headers=header);#chardet的编码检测response.encoding = response.apparent_encoding;response.raise_for_status();return response.text;def write_txt(file_name,content):with open(file_name, 'a+') as file:# 过滤掉内容是换行符的内容if content != "\n" and content != "\r":# 过滤每行的内容里包含的换行符content = re.sub('\n|\r','',content);file.write(content + '\n')if __name__ == '__main__':# selenium_main("春秋我为王")# selenium_main("秦吏")selenium_main("汉阙")print('爬取完成')
1.python爬取笔趣阁小说相关推荐
- python爬取笔趣阁小说(附源码)
python爬取笔趣阁小说 文章目录 python爬取笔趣阁小说 前言 一.获取小说目录结构 获取目录连接 请求代码 解析目录 XPath tqdm 解析 二.获取小说章节结构 请求代码 解析章节 代 ...
- python爬取小说爬取_用python爬取笔趣阁小说
原标题:用python爬取笔趣阁小说 首先打开笔趣阁网址,链接,搜索自己想要的小说. 在网站内单击右键,点击检查,会出现如下界面! 我们需要的章节信息就在我划的这块, 可以将每个标签点一下,它对应的内 ...
- Python爬取笔趣阁小说,有趣又实用!
上班想摸鱼?为了摸鱼方便,今天自己写了个爬取笔阁小说的程序.好吧,其实就是找个目的学习python,分享一下. 1. 首先导入相关的模块 import os import requests from ...
- 用python爬取笔趣阁小说并分章节保存到本地
在宿舍无聊时想做点小程序,刚好又看到笔趣阁的广告,就想着爬一下小说看看,通过网上的爬取教程整理的 使用beautifulsoup解析request获取的HTML http://beautifulsou ...
- Python爬取笔趣阁小说2.0版
之前的爬虫文章中,我们只可以爬取某本特定的小说,小波大叔一般喜欢看玄幻和修真类的,那么想把这一类小说全部爬下来该怎么操作呢,2.0版本来了,依然还是笔趣阁网站,初学者而言,这个没有反扒机制,比较方便. ...
- 通过python爬取笔趣阁小说,获取图片保存本地,数据保存mysql
通过python爬取小说图片.小说名称.作者.章节.内容.直接上代码 import requests import time from bs4 import BeautifulSoup from qu ...
- 1-4 python爬取笔趣阁小说(附带完整代码)
笔趣看是一个盗版小说网站,这里有很多起点中文网的小说,该网站小说的更新速度稍滞后于起点中文网正版小说的更新速度.并且该网站只支持在线浏览,不支持小说打包下载.所以可以通过python爬取文本信息保存, ...
- python爬取笔趣阁小说的代码微小调整修改
原文来自: https://blog.csdn.net/u012717715/article/details/92811743 本人说明:其实严格地这不是转载,实际上更应该算是原创!原文代码不能正常 ...
- python 爬取笔趣阁小说(TK可视化)
import requests from lxml import etree from pyquery import PyQuery as pq import re import time from ...
最新文章
- 第十三周项目二-动物这样叫(1)
- 为什么使用pickle模块
- 【渝粤教育】电大中专电大中专沟通技巧考试考核试题 (2)作业 题库
- 读《编程之美》读后感3
- mvc5 @html,如何在MVC 5中使用 HTML5 Viewer
- 【kafka】Kafka leader -1
- Transactional replication-如何跳过一个事务
- 中兴f477v2超级管理员_中兴f677v2联通光猫超级密码及登录地址
- WIN10 修改用户下文件夹的名称
- 让传感器数据在三维地图上显示,更直观,更震撼!
- 使用mplayer做影片预览图
- 软考中级-软件设计师知识点与例题-1、计算机组成与结构
- java压缩mp4大小_压缩的mp4视频播放时间太长(exoplayer)
- totolinkn200up怎么设置_TOTOLINK N200UP无线网卡驱动
- 电视剧《大秧歌》随感
- android 判断APP是否第一次打开
- 基于JAVA的停车场管理系统
- 分享一个竞品分析报告
- 移动浏览器内核及连接数
- c语言单链表设计报告,单链表实验报告