一直都说想学爬虫,前两天就开始认真在B站看了一下爬虫,其实之前也看过一点,但是之前看的那个是用urllib的 用起来就比较麻烦.然后这次在B站找到的一个还不错,直接奉上链接吧:https://www.bilibili.com/video/BV1Yh411o7Sz
到目前为止看到了bs4的实战(其实还没有开始看这一集), 因为看了前面的requests 正则 bs4的简单的基础内容之后,我觉得我可以完成这一集的实战内容,就利用中午休息的时间完成了这一集的内容(可能效率会代码慢了点)总的来说还算是成功的.走了走了继续看爬虫了
以下就是爬取三国演义所有内容的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# 需求: 爬取三国演义小说所有的章节标题和章节内容 import requests from bs4 import BeautifulSoup import os if not os.path.exists('./三国演义'): os.mkdir('./三国演义') url = 'https://www.shicimingju.com/book/sanguoyanyi.html' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36' } # a标签链接储存列表 list_link = [] # 页面提取 -> obj list_page = requests.get(url=url, headers=headers).text soup = BeautifulSoup(list_page, 'lxml') # 提取所有a标签 list_a = soup.select('.book-mulu a') # 遍历a标签并提取链接储存 for i in range(len(list_a)): article_page = requests.get(url='https://www.shicimingju.com' + soup.select('.book-mulu a')[i]['href'], headers=headers).text # 获取目录得到的内容页链接 article_soup = BeautifulSoup(article_page, 'lxml') title = article_soup.find('h1').get_text() # 定位标题并提取文本 title = title + '.txt' # 创建txt文件名 article = article_soup.find('div', class_='chapter_content').get_text() # 定位内容并提取文本 article_path = './三国演义/' + title # 设定保存路径 # 持久化存储 with open(article_path, 'w', encoding='utf-8') as fp: fp.write(article) print(title, '下载完成!!!') print('Over!!!') |