python3 用requests、BeautifulSoup库爬取小说

 以爬取某小说网为例,爬取小说《女总裁的全能兵王

要引用库requests、BeautifulSoup

import requests
from bs4 import BeautifulSoup

进入目录https://www.17k.com/list/1741975.html

寻找html上对应章节的url

代码

import requests
from bs4 import BeautifulSoup
url = 'https://www.17k.com'
r = requests.get("https://www.17k.com/list/1741975.html");//获取html
r.encoding = 'utf-8';

soup = BeautifulSoup(r.text, 'html.parser');

dl = soup.find_all('dl', class_="Volume")//寻找所有标签dl以及class是Volume

aTags = dl[1].find_all('a', target="_blank")//寻找所有的带有href连接的a标签
for x in aTags:
     print(x['href']);//打印连接

打印结果:

进入其中一个章节,寻找小说文本规则

完整代码

import requests
from bs4 import BeautifulSoup
url = 'https://www.17k.com'
# r = requests.get("https://www.17k.com/list/3006464.html");
r = requests.get("https://www.17k.com/list/1741975.html");
r.encoding = 'utf-8';
# print(r.text);
soup = BeautifulSoup(r.text, 'html.parser');
# print(soup);
dl = soup.find_all('dl', class_="Volume")
print(len(dl))
# dl_soup = BeautifulSoup(dl);
aTags = dl[1].find_all('a', target="_blank")
for x in aTags:
    # print(x.get_text());
    print(x['href']);
    # 获取子章节内容
    r = requests.get(url + x['href']);
    r.encoding = 'utf-8';
    # print(r.text);
    # 解析子章节
    soup = BeautifulSoup(r.text, 'html.parser');
    # 获取小说章节对应文本div
    div = soup.find_all('div', class_="readAreaBox content");
    # 查询标题写入文本
    h1 = div[0].find_all('h1');
    f = open('D:\\CODE\\pyWordSpace\\XS2.txt', 'a');
    # print(h1)
    f.write(h1[0].get_text() + '\n');
    print(div[0]);
    # 查询所有小说文本标签p
    divp = div[0].find_all('div', class_="p");
    ps = divp[0].find_all('p');
    # for循环把p写入文本
    for y in ps:
        f = open('D:\\CODE\\pyWordSpace\\XS2.txt', 'a');
        f.write(y.get_text() + '\n');

爬取结果:

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值