目录
1.解析
1.数据分类
1.结构化数据
特点:有固定的格式:HTML XML
2.非结构化数据
示例:图片 音频 视频,这类数据一般存储为二进制
with open("girl.jgp","wb") as f:
f.write(html)
2.正则表达式re
1.使用流程
1.创建编译对象:p = re.compile('\d')
2.对已有的字符串匹配:result = p.match("123ABC")
3.获取匹配结果:print(result.group())
2.常用方法
1.match(s):只匹配字符串开头,返回对象
2.search(s):从开始往后去匹配第一个,返回对象
3.group():从match和search返回的对象中取值
4.findall(s):全部匹配,返回一个列表
3.表达式
. 任意字符(不能匹配\n)
[...] 包含[]内容 A[BCD]E --> ABE ACE ADE
\d 数字
\w 字母\数字\下划线
\s 空白字符
\S 非空字符
* 前一个字符出现0次或多次
? 0次或一次
+ 1次或多次
{m} 前一个字符出现m次
贪婪匹配:整个表达式匹配成功前提下,尽可能多的去匹配*
非贪婪匹配:整个表达式匹配成功前提下,尽可能少的去匹配*
4.示例
"""<div><p>仰天大笑出门去,我辈岂是蓬蒿人</p></div>
<div><p>天生我材必有用,千金散尽还复来</p></div>"""
import re
s = """<div><p>仰天大笑出门去,我辈岂是蓬蒿人</p></div>
<div><p>天生我材必有用,千金散尽还复来</p></div>"""
# 非贪婪匹配
p = re.compile('<div>.*?</div>',re.S)
result = p.findall(s)
print(result) # 列表中2个元素
# 创建编译对象,贪婪匹配
p = re.compile('<div>.*</div>',re.S)
result = p.findall(s)
print(result) # 列表中1个元素
5.findall()的分组
1.先按整体匹配出来
2.如果有2个或多个(),则以元组的方式去显示
import re
s = "A B C D"
p1 = re.compile('\w+\s+\w+')
print(p1.findall(s))
# 1.按整体去匹配 ['A B','C D']
# 2.显示括号()中内容 ['A','C']
p2 = re.compile('(\w+)\s+\w+')
print(p2.findall(s))
# 1.整体匹配 :['A B','C D']
# 2.显示括号内容 :[('A','B'),('C','D')]
p3 = re.compile('(\w+)\s(\w+)')
print(p3.findall(s))
6.练习
1.猫眼电影 - top100榜单
2.目标:电影名 主演 上映时间
3.步骤
1.找URL
第1页:http://maoyan.com/board/4?offset=0
第2页:http://maoyan.com/board/4?offset=10
第n页:http://maoyan.com/board/4?offset=(n-1)*10
2.用正则去匹配相应内容
'<div class="movie-item-info">.*?title="(.*?)".*?class="star">(.*?)</p>.*?class="releasetime">(.*?)<(.*?)</p>.*?</div>',re.S
3.写代码
1.获取每页html源码
2.正则处理html源码
3.写入本地文件
2.Fiddler抓包工具
1.抓包设置
1.设置Fiddler抓包工具
1.HTTPS:Tools -> HTTPS ->...from browsers only ->Actions证书信任
2.connections :设置端口号:8888
2.设置浏览器代理
Proxy SwitchOmega - 选项 - 新建情景模式 - HTTP 127.0.0.1 8888 - 应用
2.Fiddler常用菜单
1.Inspector:查看抓到数据包的详细内容
2.常用选项
1.Headers:客户端发送到服务器的header,包含web客户端信息 cookie 传输状态
2.WebForm:显示请求的POST的数据
3.Raw:将整个请求显示为纯文本
3.请求方式及案例
1.GET(查询参数都在URL地址中显示)
2.POST
1.特点:查询参数在Form表单里保存
2.使用
urllib.request.Request(url,data=data,headers=headers)
data:表单数据data必须为 bytes 类型提交,不能是字典
3.案例:有道翻译
1.利用Fiddler抓包工具抓取 WebForms 里面表单数据
2.对POST数据进行处理 bytes 数据类型
3.发请求得响应
4.json模块
json.loads("json格式的字符串")
作用:将json格式的字符串 -> Python字典
3.Cookie模拟登陆
1.Cookie和Session
cookie:通过在客户端记录的信息确定用户身份
session:通过在服务器端记录的信息确定用户身份
2.案例:使用cookie模拟登陆人人网
1.获取到登陆信息的cookie(登陆1次抓包)
4.requests模块
1.安装(Conda prompt终端)
1.(base) > conda install requests
(base) > pip install requests
2.常用方法
1.get() : 向网站发起请求,并获取响应对象
1.用法:response = request.get(url,headers=headers)
2.response的属性
1.response.text:获取响应内容(字符串)
一般默认返回字符编码:ISO-8859-1
手动指定:response.encoding = "utf-8"
2.response.content:获取响应内容(bytes)
1.应用场景:爬取图片,音频等非结构化数据
2.示例:爬取百度美女图片
1.找url
3.response.status_code:返回服务器响应码
2.post()
5.作业
1. 爬取内涵段子
网址 :http://www.neihan8.com
段子 --- 内涵段子
存放到本地文件
用正则去匹配
爬取有道翻译POST案例
from urllib import request,parse
import json
# 处理表单数据
# Form表单的数据要放到字典中,然后再进行编码转换
word = input("请输入要翻译的内容:")
data = {"i":word,
"from":"AUTO",
"to":"AUTO",
"smartresult":"dict",
"client":"fanyideskweb",
"salt":"1536648321283",
"sign":"1e7948e25551448dbfb7184f23dc126c",
"doctype":"json",
"version":"2.1",
"keyfrom":"fanyi.web",
"action":"FY_BY_REALTIME",
"typoResult":"false"
}
# 把data转为 bytes 数据类型
# decode为字符串,encode为bytes
data = parse.urlencode(data).encode("utf-8")
# 发请求 得响应
# 此处URL为抓包工具抓到的 POST的URL
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
headers = {"User-Agent":"Mozilla5.0/"}
req = request.Request(url,data=data,headers=headers)
res = request.urlopen(req)
# result为json格式的字符串
result = res.read().decode("utf-8")
# 把json格式的字符串转换为 Python字典
# json模块中的loads方法 :json格式字符串 -> Python字典
result_dict = json.loads(result)
#print(result_dict)
#{'type': 'ZH_CN2EN',
# 'errorCode': 0,
# 'elapsedTime': 0,
# 'translateResult': [[{'src': '你好', 'tgt': 'hello'}]]}
r = result_dict["translateResult"][0][0]["tgt"]
print(r)
人人网cookie模拟登陆
from urllib import request
url = "http://www.renren.com/967469305/profile"
headers = {"Host":"www.renren.com",
"Connection":"keep-alive",
"Upgrade-Insecure-Requests":"1",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Referer":"http://www.renren.com/SysHome.do",
#Accept-Encoding: gzip, deflate
"Accept-Language":"zh-CN,zh;q=0.9",
"Cookie":"anonymid=jlxb586t8i3v0g; depovince=BJ; _r01_=1; JSESSIONID=abcqRp76SQcK0dfdzQhxw; ick_login=4165cad5-4fdc-466c-a7d0-98e014715ff0; first_login_flag=1; ln_uact=13603263409; ln_hurl=http://head.xiaonei.com/photos/0/0/men_main.gif; loginfrom=syshome; jebe_key=094486d9-6cd0-442c-a7d4-c9115c822ab7%7C2012cb2155debcd0710a4bf5a73220e8%7C1536653132046%7C1%7C1536653131904; wp_fold=0; wp=0; jebecookies=8314ca50-d39d-4df1-b9fa-ea391456cc38|||||; _de=4DBCFCC17D9E50C8C92BCDC45CC5C3B7; p=356eafd62d5adaeb90370c13491ac9055; t=b963e2106aa3249e5289deba7f486e915; societyguester=b963e2106aa3249e5289deba7f486e915; id=967469305; xnsid=3850523b"
}
req = request.Request(url,headers=headers)
res = request.urlopen(req)
html = res.read().decode("utf-8")
print(html)
request模块示例
import requests
url = "http://www.baidu.com/"
headers = {"User-Agent":"Mozilla5.0/"}
# 发请求获响应对象
response = requests.get(url,headers=headers)
response.encoding = "utf-8"
# 获取响应内容,text返回字符串
#print(response.text)
# content返回bytes
#print(response.content)
print(response.status_code)
5.作业答案
import requests
import re
class NeihanSpider:
def __init__(self):
self.baseurl = "https://www.neihan8.com/article/index"
self.page = 1
self.headers = {"User-Agent":"Mozilla5.0/"}
def getPage(self, url):
res = requests.get(url,headers=self.headers)
res.encoding = "utf-8"
html = res.text
self.parsePage(html)
def parsePage(self,html):
p = re.compile('<div class="desc">(.*?)</div>')
r_list = p.findall(html)
self.writePage(r_list)
def writePage(self,r_list):
for r_str in r_list:
with open("内涵段子.txt","a") as f:
f.write(r_str + "\n\n")
def workOn(self):
while True:
if self.page == 1:
url = self.baseurl + ".html"
else:
url = self.baseurl + "_" + str(self.page) + ".html"
print("正在爬取%d页" % self.page)
self.getPage(url)
print("第%d页爬取成功" % self.page)
c = input("是否继续爬取")
if c == 'y':
self.page += 1
else:
print("爬取结束")
break
if __name__ == "__main__":
spider = NeihanSpider()
spider.workOn()