爬取小说并存取为txt文件

代码:

#coding:utf-8
#author:Ericam_
import re
import sys
from bs4 import BeautifulSoup
import urllib.request
import time

headers = ('User-Agent', 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1')
opener = urllib.request.build_opener()
opener.addheaders = {headers}
urllib.request.install_opener(opener)

 
url = "http://www.xinshubao.net/66/66351/"

file = urllib.request.urlopen(url)
data = BeautifulSoup(file , from_encoding="utf8")  


# section_name = data.title.string
# print(section_name)
# print(type(str(section_name)))
# try:
#     section_text = data.select("#content p")[0].text
#     section_text=re.sub( '\s+', '\r\n\t', section_text).strip('\r\n\t')
#     section_text = section_text.replace('\t','')
#     section_text = section_text.replace('\n','')
#     section_text = section_text.replace('\r','')
# except IndexError:
#     section_text = ''
    

# print(section_text)

linklist = []
for x in data.find_all('a'):
    link = x.get('href')

    if link:
        
        if link[-1] == 'l':
           # link = 'https://www.yanqing-888.net/' + link
            linklist.append(link)

# print(linklist)


for i in linklist:
	time.sleep(2)
	
	file = urllib.request.urlopen(i)
	data = BeautifulSoup(file , from_encoding="utf8")  

	section_name = data.title.string.split('_')[1]
	print(section_name)
	sys.stdout.flush()
	try:
		section_text = data.select("#content")[0].text  
		section_text=re.sub( '\s+', '\r\n\t', section_text).strip('\r\n\t')
		section_text = section_text.replace('\t','')
		section_text = section_text.replace('\n','')
		section_text = section_text.replace('\r','')
	except IndexError:
		section_text = ''


	# fp = open('1230.txt','a')
	
	with open('1231.txt','a') as fp:

		fp.write(str(section_name))
		fp.write('\n')
		fp.write(section_text)
		fp.write('\n')

	
	sys.stdout.flush()

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值