python爬虫--正则表达式与Cookie的使用

正则表达式:描述字符串排列的一套规则

原子

1.普通字符作为原子

import re
pattern = "zjc"
string = "dajsfahfzjcsafkf"
result = re.search(pattern,string)
print(result)
<re.Match object; span=(8, 11), match='zjc'>

2.非打印字符作为原子

import re
pa = "\n"
string = '''ss
sdd'''
result =re.search(pa,string)
print(result)
<re.Match object; span=(2, 3), match='\n'>

3.通用字符作为原子

import re
pa = "\w\dpython\w"
string = '''abc1python_zjc'''
result =re.search(pa,string)
print(result)
<re.Match object; span=(2, 11), match='c1python_'>

原子表

[]:原子表(正则表达式:[xyz]py;源字符串:xpython可以匹配出xpy)

[]:代表的是除了中括号里面的原子均可以匹配([xyz]py可以匹配apy但不能匹配xpy)

import re
pa1 = "\w\dpython[xyz]\w"
pa2 = "\w\dpython[^xyz]\w"
pa3 = "\w\dpython[xyz]\W"
string = "abcd345pythonz_py"
result1 = re.search(pa1,string)
result2 = re.search(pa2,string)
result3 = re.search(pa3,string)
print(result1)
print(result2)
print(result3)
<re.Match object; span=(5, 15), match='45pythonz_'>
None
None

元字符

理解各元字符的含义

1.任意匹配元字符

"."匹配任意一个除换行符以外的任意字符

import re
pa = "...python..."
string = "abczjcpythonzjcdef"
result = re.search(pa,string)
print(result)
<re.Match object; span=(3, 15), match='zjcpythonzjc'>

2.边界限定元字符

"^“匹配字符串的开始;”$"匹配字符串的结束

import re
pa1 = "^zjc"
pa2 = "^abc"
pa3 = "zja"
pa4 = "zjc$"
pa5 = "zja$"
string = "zjcabcdefgzjc"
result1 = re.search(pa1,string)
result2 = re.search(pa2,string)
result3 = re.search(pa3,string)
result4 = re.search(pa4,string)
result5 = re.search(pa5,string)
print(result1)
print(result2)
print(result3)
print(result4)
print(result5)

<re.Match object; span=(0, 3), match='zjc'>
None
None
<re.Match object; span=(10, 13), match='zjc'>
None

3.限定符

%%html
<img src = "./1.png",width=320, heigth=240>

<img src = “./1.png”,width=320, heigth=240>

4.模式选择符

import re
pa = "python|zjc"
string1 = "zjcsdassdpythonad"
string2 = "pythonasdazjcasd"
result1 = re.search(pa,string1)
result2 = re.search(pa,string2)
print(result1)
print(result2)

<re.Match object; span=(0, 3), match='zjc'>
<re.Match object; span=(0, 6), match='python'>

5.模式单元符

import re
pa1 = "(cd){1,}"
pa2 = "cd{1,}"
string = "asdcdcdcdcdasdas"
result1 = re.search(pa1,string)
result2 = re.search(pa2,string)
print(result1)
print(result2)
<re.Match object; span=(3, 11), match='cdcdcdcd'>
<re.Match object; span=(3, 5), match='cd'>

模式修正

from PIL import Image
im = Image.open("C:/Users/Administrator/Desktop/临时src/3.png")
im.show()

贪婪模式与懒惰模式

import re
pa1 = "p.*y"#贪婪模式
pa2 = "p.*?y"#懒惰模式
string = "psadaydasyadsadyasd"
result1 = re.search(pa1,string)
result2 = re.search(pa2,string)
print(result1)
print(result2)
<re.Match object; span=(0, 16), match='psadaydasyadsady'>
<re.Match object; span=(0, 6), match='psaday'>

正则表达式常见函数

1.re.match函数 起始位置匹配一个模式

import re
pa1 = ".zjc."
string = "aZjcssdzjcsd"
result1 = re.match(pa1,string,re.I)
result2 = re.match(pa1,string,re.I).span()
print(result1)
print(result2)
<re.Match object; span=(0, 5), match='aZjcs'>
(0, 5)

2.全局匹配函数

(1)使用re.compile()进行预编译
(2)使用findall()找出所有匹配结果

import re
string = "sdadzjcasdaszjcasdasdazjcasdasazjcasd"
pa =re.compile(".zjc.") 
result = pa.findall(string)
print(result)
['dzjca', 'szjca', 'azjca', 'azjca']

3.re.sub()函数

re.sub(pattern,想替换的字符串,string,最多替换次数)--------------最多替换次数可不写,将会全部替换

import re
string = "python1111python2222python"
pattern="python"
result1 = re.sub(pattern,"java",string,2)
result2 = re.sub(pattern,"php",string)
print(result1)
print(result2)
java1111java2222python
php1111php2222php

常见实例解析

实例1:匹配网址

\s* 0个以上空格符
[^\s]* 除了空格符之外的任意字符,0个以上

import re
pattern = "[a-zA-Z]+://[^\s]*[.com|.cn]"
string = "<a href = 'http://www.baidu.com'>百度首页 </a>"
result = re.search(pattern,string)
print(result)
<re.Match object; span=(11, 31), match='http://www.baidu.com'>

实例2:匹配电话号码

import re
pattern  = "\d{4}-\d{7}|\d{3}-\d{8}"#匹配电话号码的正则表达式
string = "021-3587453546564"
result = re.search(pattern,string)
print(result)
<re.Match object; span=(0, 12), match='021-35874535'>

实例3:匹配电子邮箱地址

import re
pattern = "\w+([.+-]\w+)*@\w+([.-]\w+)*\.\w+([.-]\w+)*"
string = "[email protected]"
result = re.search(pattern,string)
print(result)
<re.Match object; span=(0, 43), match='[email protected]'>

匹配9位或者10位号码QQ邮箱

import re
pattern = "(\d{10}|\d{9})@qq.com"
string = "asdlf234lmasf1262735123@@[email protected]"
result = re.search(pattern,string)
print(result)
<re.Match object; span=(31, 48), match='[email protected]'>

什么 是Cookie

在爬虫的使用中,如果涉及登录等操作, 经常会使用到Cookie。

那么什么是Cookie呢?

简单来说,我们访问每一个 互联网页面,都是通过HTTP协议进行的,而HTTP协议见一个 无状态协议,所谓的无状态协议即无法维持会话之间的状态。

比如,仅使用HTTP协议的话,我们登录一个网站的时候,假如登录成功了,但是当我们访问该网站的其他网页的时候,该登录状态则会消失,此时还需要再登录一一次, 只要页面涉及更新,就需要反复的进行登录,这是非常不方便的。

所以此时,我们需要将对应的会话信息,比如登录成功等信息通过一些方式保存下来,比较常用的方式有两种:通过Cookie保存会话信息或通过Session保存会话信息。

1.无cookie处理的登陆

import urllib.request
import urllib.parse
url = "http://bbs.chinaunix.net/forum-216-1.html"
postdata = urllib.parse.urlencode({"username":"weisuen","password":"aA123456"}).encode('utf-8')
req = urllib.request.Request(url,postdata)
req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36")
data = urllib.request.urlopen(req).read()
fhandle = open("C:/Users/Administrator/Desktop/爬虫学习/cookie1.html","wb")
fhandle.write(data)
fhandle.close()
url2 = "http://bbs.chinaunix.net/"
req2 = urllib.request.Request(url2,postdata)
req2.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36")
data = urllib.request.urlopen(req2).read()
fhandle = open("C:/Users/Administrator/Desktop/爬虫学习/cookie2.html","wb")
fhandle.write(data2)
fhandle.close()

为什么会出现这种情况呢?是因为在这里,我

们没有设置Cookie处理,而HTTP协议是一个无状态协议,我们访问了新网页,自然会话信息会消失。

如果希望登录状态一直保持, 则需要进行Cookie处理。

进行Cookie处理的一种常用思路如下:

1)导人Cookie处理模块http cokiejaro

2)使用http.cookiejar.CookieJarO创建CookieJar对象。

3)使用HTTPCookieProcessor创建cookie处理器,并以其为参数构建opener对象4)创建全局默认的opener对象。

所以,上面一个实例的代码可以改进为:

import urllib.request
import urllib.parse
import http.cookiejar
url = "http://bbs.chinaunix.net/forum-216-1.html"
postdata = urllib.parse.urlencode({"username":"weisuen","password":"aA123456"}).encode('utf-8')
req = urllib.request.Request(url,postdata)
req.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36")
#创建Cookiejar对象
cjar = http.cookiejar.CookieJar()
#创建cookie处理器,并以opener为对象
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cjar))
#将opener安装为全局
urllib.request.install_opener(opener)
data = urllib.request.urlopen(req).read()
fhandle = open("C:/Users/Administrator/Desktop/爬虫学习/cookie3.html","wb")
fhandle.write(data)
fhandle.close()
url2 = "http://bbs.chinaunix.net/"
req2 = urllib.request.Request(url2,postdata)
req2.add_header("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36")
data = urllib.request.urlopen(req2).read()
fhandle = open("C:/Users/Administrator/Desktop/爬虫学习/cookie4.html","wb")
fhandle.write(data2)
fhandle.close()

在cookie这两个例子我并没有完全理解,最终结果不知道由于什么原因没有得到正确结果

原创文章 31 获赞 60 访问量 3098

猜你喜欢

转载自blog.csdn.net/qq_40651017/article/details/105785536
今日推荐