我的第一个python爬虫

我的第一个python爬虫## 标题
由于是初学python爬虫,就写了一个爬取诗词名句网小说的程序

import urllib.request
import urllib.parse
from bs4 import BeautifulSoup
import time

def get(herf):
    requests = urllib.request.urlopen(herf).read().decode('utf8')
    soup = BeautifulSoup(requests, 'lxml')
    ao=soup.find('div',class_='chapter_content')
    return ao
url = 'http://www.shicimingju.com/book/sanguoyanyi.html'
request=urllib.request.urlopen(url).read().decode('utf8')
soup=BeautifulSoup(request,'lxml')   #解析request
# print(soup)
lists=soup.select('.book-mulu > ul > li > a')  #用.select()筛选所需内容
# print(lists[1])
n=len(lists)
f = open('G://三国演义1.txt', 'a',encoding='utf8')
f.write('\t'*8+'三国演义'+'\n')  #'\t'*8是为了让章节名字居中,写入书名
for i in range(1,n+1):
    herf='http://www.shicimingju.com/book/sanguoyanyi/'+str(i)+'.html' #构建章节内容url
    lr=get(herf).get_text()   #发送请求获取章节内容,用get_text提取出去标识符的TXT内容
    le=lists[i-1].get_text()  #由于lists是列表,章节名第一回放在list[0]
    f = open('G://三国演义1.txt', 'a',encoding='utf8')
    f.write('\n'+'\t'*6+str(le)+'\n'+lr)  #'\t'*6是为了让章节名字居中
    time.sleep(2)  #降低请求频率
    print(le+'......')
    # print(lr)
f.close()

这个爬虫是我的练习之作,接下来有时间会对它进行一些改进


  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值