我的第一个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()
这个爬虫是我的练习之作,接下来有时间会对它进行一些改进