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

声明:爬虫为学习使用,请各位同学务必不要对当放网站或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可以持
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值