1、python输入
使用input()函数,括号内可以包括输入的提示语句(特别注意输入法的问题,与,)
a,b,c = input("请输入三个值以,作为分割符:").split(",")
print(a)
print(b)
print(c)
2、判断数据类型
判断是不是字符串
type('q')is str
isinstance('q',str)
3、python正则表达式
import re
a = '''asdfsafhellopass:
234455
worldafdsf
'''
b = re.findall('hello(.*?)world',a)
c = re.findall('hello(.*?)world',a,re.S)
print 'b is ' , b
print 'c is ' , c
运行结果如下:
b is []
c is ['pass:\n\t234455\n\t']
4、python获取网页编码(encoding和apparent_encoding)
encoding是根据title中的charset返回,如果没有返回ISO-8859-1
apparent_encoding是根据正文来计算,较为准确
5、for循环使用 enumerate 函数 获取下标index
s=['a','b','c']
for i, si in enumerate(s):
print(i+“,”+si)
#0,a 1,b 2,c
#s为一个列表,i是下标从0开始,si是迭代.next内容
6、爬虫乱码
data = resp.text.encode("latin1").decode("utf-8")
#Latin1是ISO-8859-1的别名
##将原文件转码成latin1编码(使用encode函数) ,再解码成gbk编码(使用decode函数)
python 爬取小说
#爬取小说追忆逝水流年
import requests
import re
#爬取的网址主页
url = "http://www.pgyzw.com/html/13/13352/index.html"
resp = requests.post(url)
#设置响应编码格式
resp.encoding = "gbk"
resp = resp.text
#从结果list中过滤出网址,并添加前缀
resp = re.findall(r'<table border="0" align="center" cellpadding="3" cellspacing="1" class="acss">.*?</table>', resp, re.S)[0]
#保留7位数字.html
urllist = re.findall(r'[0-9]{7}.html',resp)
#获取urllist的长度
urllistl = len(urllist)
#得到的网址加入前缀http://www.pgyzw.com/html/13/13352/
for i in range(0,urllistl):
urllist[i] = 'http://www.pgyzw.com/html/13/13352/'+urllist[i]
#新建文件预备写入
f = open("C:/Users/j/Desktop/追忆逝水流年.txt","w")
#按照网址list依次爬取,写入
for i in range(0,urllistl):
#爬出整个网页
resp = requests.post(urllist[i])
resp.encoding = "gbk"
resp = resp.text
#提取正文并处理
respcontext = re.findall(r'<div id="content" style="width:67%; margin:0 auto; text-align:"> .*?</div>',resp,re.S)[0]
#过滤掉标题开头
respcontext = respcontext.replace('<div id="content" style="width:67%; margin:0 auto; text-align:"> ',"")
#html对应的换行、空格替换成普通文本的换行、空格
respcontext = respcontext.replace("<br />","\n")
respcontext = respcontext.replace(" "," ")
respcontext = respcontext.replace("</div>","\n")
#过滤的爬取结果写入文件
f.write(respcontext)
爬取图片
#图片
import requests
import re
from urllib import request
#爬取网址主页
url = "http://www.huitu.com/topic-detail/2885.html?recType=0"
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'
}
html=requests.get(url, headers=headers)
#设置响应编码格式
html.encoding = "utf-8"
html = html.text
html = re.findall(r'<div class="seozone">.*?</div>',html,re.S)[0]
urllist = re.findall(r'http://www.huitu.com/design/show/.*?.html',html)
urllen = len(urllist)
#分页爬取得到图片的资源位置src
src = []
for i in range(0,urllen):
resp1 = requests.get(urllist[i])
resp1 = resp1.text
resp1 = re.findall(r'<img class="m-img".*?/>',resp1,re.S)[0]
resp1 = re.findall(r'http://.*?.jpg',resp1,re.S)[0]
src.append(resp1)
#依照图片src下载图片
for i in range(0,len(src)):
with open("C:/Users/p/Desktop/photo/"+str(i)+".jpg",'wb') as f:
r = requests.get(src[i])
f.write(r.content)