爬虫入门实例:利用requests库爬取笔趣小说网

w3cschool上的来练练手,爬取笔趣看小说http://www.biqukan.com/

爬取《凡人修仙传仙界篇》的所有章节

1.利用requests访问目标网址,使用了get方法

2.使用BeautifulSoup解析返回的网页信息,使用了BeautifulSoup方法

3.从中获取我们需要的小说内容,使用了find,find_all等方法

4.进行格式化处理,主要是python里字典和列表的运算

5.保存到txt文件,涉及一些简单的文件操作,open,write等

 

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import os


class NovelSpider:
    def __init__(self):
        self.start_url = 'https://www.biqukan.com/1_1680/'

    def get_novel(self):
        # 访问起始URL
        response = requests.get(self.start_url)
        # 这里用lxml解析器会出问题,找了好久才发现。。。
        soup = BeautifulSoup(response.text, 'html.parser')
        # print(response.text)
        div_chapter = soup.find(class_="listmain")
        # print(div_chapter)
     # 选取所有的a标签,a标签包含所有章节名称和URL chapter_list
= div_chapter.find_all('a') # 这里去除前12个重复的章节(具体看html代码) chapter_list = chapter_list[12:] #print(chapter_list) chapter = [] # 记录总章节数,下载显示完成率 chapter_num = len(chapter_list) # 设置计数器 count = 0 # 循环对每个章节进行访问和下载 print('《凡人修仙传仙界篇》开始下载:') for cl in chapter_list: chapter_dict = {} chapter_name = cl.get_text() # 抓取章节名称 chapter_dict['name'] = chapter_name chapter_url = cl.get('href') # 抓取章节URL地址 chapter_dict['value'] = 'https://www.biqukan.com' + chapter_url if chapter_dict not in chapter: chapter.append(chapter_dict) print(f"已下载:{count}/{chapter_num}") # 调用download_novel(),按章节下载小说 self.download_novel(chapter_dict) # 同时计数器加一 count += 1 def parse_novel(self, url): # 小说章节的具体内容是动态加载的,用Phantom访问 browser = webdriver.PhantomJS(executable_path=r'F:\Spider\novelSpider\phantomjs.exe') browser.get(url) soup = BeautifulSoup(browser.page_source, 'html.parser') find_txt = soup.find(class_='showtxt') # print(type(find_txt.get_text())) return find_txt.get_text() def download_novel(self, data): # data是{name:章节名,value:章节url地址}的字典 filename = data['name'] url = data['value'] # 通过url访问小说章节的具体内容,返回小说内容,str txt = self.parse_novel(url) # 设置下载存储路径 path = r"F:\Spider\novelSpider" # 检查路径是否存在,否则创建新的文件夹 isExists = os.path.exists(path) if not isExists: # print('创建了新的文件夹') os.mkdir(path) else: # print('文件夹已存在') pass # 保存txt文件 with open(path + f'\凡人修仙传仙界篇.txt', 'a', encoding='utf-8') as f: # print(f'正在下载--{filename}') f.write(f'{filename}\n\n') f.write(txt) # 章节分割线 f.write('\n======\n\n') f.close() if __name__ == '__main__': ns = NovelSpider() ns.get_novel()

下载真的是超级慢,,,好像是PhantomJS访问花时间,,有待学习和改进!

posted @ 2018-10-29 15:53  toHeart  阅读(1705)  评论(0编辑  收藏  举报