python用字符串操做20行代码简单爬虫入门+案例(爬取一章《三体》小说)

clipboard.png

所须要的简单的方法

一、#导入专用包

import urllib.request

二、try...except..

try:
   语句1....
except Exception as e:
    语句2...
尝试执行语句1,执行不成功就执行语句2

三、urlopen获取内容

response =urllib.request.urlopen(webList)
#获取webList页面的内容

四、read()读取

response.read()
#读取获取的内容

五、decode解码

decode('UTF-8')
#用utf-8的方式解码

六、替换方法

html = html.expandtabs()
#html内容替换全部的制表符为空

html =html.replace(' ','')
#替换掉全部的空格

七、获取长度

lenth = len(html)
#获取文档的长度

八、find()查找方法

lenth = len(html)
#获取文档的长度

九、字符串的截取

html[0:index2]
#对整篇字符串进行截取

十、写入 open..write

writeFile =open('三体.txt','w')
writeFile.write(htm)
#写入文件

案例爬取一页《三体》小说。

#导入专用包
import urllib.request
#须要链接的页面
webList ='http://www.51shucheng.net/kehuan/santi/santi1/174.html'
#用try尝试去链接
try:
    response =urllib.request.urlopen(webList)
    #若是能成功链接,并获取内容,response就是咱们所获取的那个页面
except Exception as e:
    print('获取失败')
    #不然就打印出‘获取失败’
html = str(response.read().decode('UTF-8'))
# 把获取的内容读取出来,而且用UTF-8解码
html = html.expandtabs()
#替换掉全部的TAB符号
html =html.replace(' ','')
#替换掉全部的空格
print(html)
#能够打印出来预览一下,方便进行定位
lenth = len(html)
#获取文档的长度
html = html[html.find('neirong">',0,lenth)+9:]
index =html.find('跟鞋。</p>',0)+3
index2 = html.find('眷恋着天空。</p>')
index3 =html.find('<p>“红色联合”的战士们欢呼起来')
#找到一些关键位置,获取索引,方便下边进行定位
htm =str(html[0:index2]+html[index3:index])
#对整篇字符串进行截取
htm = htm.replace('<p>','    ')
htm = htm.replace('</p>','\n')
#把文中的<p></p>替换掉
writeFile =open('三体.txt','w')
writeFile.write(htm)
#写入文件
print('写入完成')

clipboard.png

相关文章
相关标签/搜索