# coding: utf-8'''笔趣网小说下载仅限用于研究代码勿用于商业用途请于24小时内删除'''import requestsimport osfrom bs4 import BeautifulSoupimport timedef book_page_list(book_id): ''' 通过传入的书号bookid,获取此书的所有章节目录 :param book_id: :return: 章节目录及章节地址 ''' url = 'http://www.biquw.com/book/{}/'.format(book_id) headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36'} response = requests.get(url, headers) response.encoding = response.apparent_encoding response = BeautifulSoup(response.text, 'lxml') booklist = response.find('div', class_='book_list').find_all('a') return booklistdef book_page_text(bookid, booklist): ''' 通过书号、章节目录,抓取每一章的内容并存档 :param bookid:str :param booklist: :return:None ''' try: for book_page in booklist: page_name = book_page.text.replace('', '') page_id = book_page['href'] time.sleep(3) url = 'http://www.biquw.com/book/{}/{}'.format(bookid,page_id) headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36'} response_book = requests.get(url, headers) response_book.encoding = response_book.apparent_encoding response_book = BeautifulSoup(response_book.text, 'lxml') book_content = response_book.find('div', id="htmlContent") with open("./{}/{}.txt".format(bookid,page_name), 'a') as f: f.write(book_content.text.replace('\xa0', '')) print("当前下载章节:{}".format(page_name)) except Exception as e: print(e) print("章节内容获取失败,请确保书号正确,及书本有正常内容。")if __name__ == '__main__': bookid = input("请输入书号(数字):") # 如果书号对应的目录不存在,则新建目录,用于存放章节内容 if not os.path.isdir('./{}'.format(bookid)): os.mkdir('./{}'.format(bookid)) try: booklist = book_page_list(bookid) print("获取目录成功。
") time.sleep(5) book_page_text(bookid, booklist) except Exception as e: print(e) print("获取目录失败,请确保书号输入正确。
")
程序运行之后,在控制台输入书号,即可开始进行抓取了。在本地也会自动新建一个书号命名的文件夹,在该文件夹下,会存放小说的章节,如下图所示。三、常见问题在运行过程中小伙伴们应该会经常遇到这个问题,如下图所示。这个是因为访问太快,网站给你反爬了。可以设置随机的user-agent或者上代理等方法解决。四、总结我是Python进阶者。这篇文章主要给大家介绍了小说内容的获取方法,基于网络爬虫,通过requests爬虫库和bs4选择器进行实现,并且给大家例举了常见问题的处理方法。小伙伴们,快快用实践一下吧。如果在学习过程中,有遇到任何问题,欢迎加我好友,我拉你进Python学习交流群共同探讨学习。
0 评论