php爬取网页中div i下文本,爬取网页中的文章写成本地txt文件

之前看了周浩晖的一下小说,包括邪恶催眠师系列,这个系列已经到了第三季但是网上好像没找到txt文件。只找到下方网页中的文章,网页看小说不是很方便,所以决定爬下来做成txt文件放在手机中看。

http://www.txt99.com/read/12/20831/1.html

技术点:

BeautifulSoup、urllib2

直接上代码

#!/usr/bin/env python

# -*-coding:utf-8-*-

from bs4 import BeautifulSoup

import html5lib

import urllib2

import sys

import codecs

strall='';

reload(sys)

sys.setdefaultencoding('utf-8')

for i in range(1,34):

urls=str('http://www.txt99.com/read/12/20831/') +str(i) +str('.html')

html=urllib2.urlopen(urls)

htmldata=html.read()

soup=BeautifulSoup(htmldata,'html.parser',from_encoding="gb18030") #这个网页是gb2312编码,所以要转一下

#view_content_txt

titleData=soup.find ('div',id='view_content_txt')

ss=str(unicode(titleData))

lists=ss.split('

')

lings=str(lists[1])

lists2=lings.split('

')

print str(lists2[0])

strall+=str(lists2[0])

def writtetxt(content):

f = codecs.open('f:/python/1.txt', 'w', 'utf-8') #将拼接的字符串写到txt文件中

f.write(content)

# print titleData

writtetxt(strall)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值