【Python3爬虫-爬小说】爬取某小说网小说1/2--利用网址顺序抓

版权声明:== https://github.com/fyonecon == https://blog.csdn.net/weixin_41827162/article/details/84036849

声明:爬虫为学习使用,请各位同学务必不要对当放网站或i服务器造成伤害。务必不要写死循环。

-

练习目标:爬取https://b.faloo.com/BuyBook.aspx?id=526024 《我的高中女友门》

-

解释请看代码注释:

主要是网页是xxx/1.html,xxx/2.html这种数字递增的网页;小说内容在id=content这个地方。

from bs4 import BeautifulSoup
import urllib.request


def down(url, num):

    # 获取网页
    response = urllib.request.urlopen(url)
    html = response.read().decode('gbk')  # 编码格式gb2312,utf-8,GBK
    html_string = str(html)  # 转换成string,可以直接向数据库添加

    soup = BeautifulSoup(html_string, "html.parser")  # 解析网页标签

    try:
        # 匹配抓取区域
        # pid = soup.find(attrs={"id": "content"})
        pid = str(soup.findAll('div', {"id": "content"})[0])
        print("当前页数=" + str(num))
        print(type(pid))

        # 将抓取区域保存至txt文件
        fh = open('我的高中女友们.txt', 'a', encoding='utf-8')  # 制定txt编码,避免中文编码解析报错。a可以持续写入文件,w每次会覆盖之前的内容
        fh.write(pid)
        fh.close()
        print("页数=" + str(num) + "写入完成")
    except:
        print("报错页数=" + str(num))

    pass


# 有多少个该小说网页
num = 1  # 开始页
while num <= 50:  # 结束页
    down("https://b.faloo.com/p/526024/" + str(num) + ".html", num)
    num += 1
    pass
else:
    print("完成")
    pass

-

-

猜你喜欢

转载自blog.csdn.net/weixin_41827162/article/details/84036849