python爬虫学习第五章正则

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video { margin: 0; padding: 0; border: 0 }
body { font-family: Helvetica, arial, freesans, clean, sans-serif; font-size: 14px; line-height: 1.6; color: #333; background-color: #fff; padding: 20px; max-width: 960px; margin: 0 auto }
body>*:first-child { margin-top: 0 !important }
body>*:last-child { margin-bottom: 0 !important }
p,blockquote,ul,ol,dl,table,pre { margin: 15px 0 }
h1,h2,h3,h4,h5,h6 { margin: 20px 0 10px; padding: 0; font-weight: bold }
h1 tt,h1 code,h2 tt,h2 code,h3 tt,h3 code,h4 tt,h4 code,h5 tt,h5 code,h6 tt,h6 code { font-size: inherit }
h1 { font-size: 28px; color: #000 }
h2 { font-size: 24px; border-bottom: 1px solid #ccc; color: #000 }
h3 { font-size: 18px }
h4 { font-size: 16px }
h5 { font-size: 14px }
h6 { color: #777; font-size: 14px }
body>h2:first-child,body>h1:first-child,body>h1:first-child+h2,body>h3:first-child,body>h4:first-child,body>h5:first-child,body>h6:first-child { margin-top: 0; padding-top: 0 }
a:first-child h1,a:first-child h2,a:first-child h3,a:first-child h4,a:first-child h5,a:first-child h6 { margin-top: 0; padding-top: 0 }
h1+p,h2+p,h3+p,h4+p,h5+p,h6+p { margin-top: 10px }
a { color: #4183C4; text-decoration: none }
a:hover { text-decoration: underline }
ul,ol { padding-left: 30px }
ul li>:first-child,ol li>:first-child,ul li ul:first-of-type,ol li ol:first-of-type,ul li ol:first-of-type,ol li ul:first-of-type { margin-top: 0px }
ul ul,ul ol,ol ol,ol ul { margin-bottom: 0 }
dl { padding: 0 }
dl dt { font-size: 14px; font-weight: bold; font-style: italic; padding: 0; margin: 15px 0 5px }
dl dt:first-child { padding: 0 }
dl dt>:first-child { margin-top: 0px }
dl dt>:last-child { margin-bottom: 0px }
dl dd { margin: 0 0 15px; padding: 0 15px }
dl dd>:first-child { margin-top: 0px }
dl dd>:last-child { margin-bottom: 0px }
pre,code,tt { font-size: 12px; font-family: Consolas, "Liberation Mono", Courier, monospace }
code,tt { margin: 0 0px; padding: 0px 0px; white-space: nowrap; border: 1px solid #eaeaea; background-color: #f8f8f8 }
pre>code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent }
pre { background-color: #f8f8f8; border: 1px solid #ccc; font-size: 13px; line-height: 19px; overflow: auto; padding: 6px 10px }
pre code,pre tt { background-color: transparent; border: none }
kbd { background-color: #DDDDDD; background-image: linear-gradient(#F1F1F1, #DDDDDD); background-repeat: repeat-x; border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD; border-style: solid; border-width: 1px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; line-height: 10px; padding: 1px 4px }
blockquote { border-left: 4px solid #DDD; padding: 0 15px; color: #777 }
blockquote>:first-child { margin-top: 0px }
blockquote>:last-child { margin-bottom: 0px }
hr { clear: both; margin: 15px 0; height: 0px; overflow: hidden; border: none; background: transparent; border-bottom: 4px solid #ddd; padding: 0 }
table th { font-weight: bold }
table th,table td { border: 1px solid #ccc; padding: 6px 13px }
table tr { border-top: 1px solid #ccc; background-color: #fff }
table tr:nth-child(2n) { background-color: #f8f8f8 }
img { max-width: 100% }

正则表达式与Cookie的使用

正则表达式基础知识

  1. 原子
    原子是正则表达式中最基本的组成单位,每个正则表达式中至少要包含一个原子,常见的原子有以下几类:

    • 普通字符作为原子
    • 非打印字符作为原子
    • 通用字符作为原子
    • 院子表
    • 普通字符作原子的情况。普通字符比如数字、大小写字母、下划线等都可以作为原子使用。比如如下程序中,我们就使用了“yue"作为原子使用,分别是‘y‘‘u‘‘e‘。import re
      pattern="yue"
      string="http://yum.iqianyue.com"
      result1=re.search(pattern,string)
      print(result1)
    • 非打印字符作为原子
      所谓的非打印字符,指的是一些在字符串中用于格式控制的符号,比如换行符等。import re
      pattern="\n"
      string="http://yum.iqianyue.com
      http://baidu.com"
      result1=re.search(pattern.string)
      print(result1)
    • 通用字符作为原子
      所谓通用字符,即一个原子可以匹配一类字符,我们在实际项目中经常会用到这一类原子。
      | 符号 | 含义|| \w | 匹配任意一个字母、数字或下划线 |
      | \W | 匹配除了字母、数字和下划线以外的任意字符|
      | \d | 匹配任意一个十进制数|
      | \D | 匹配除了十进制数以外的任意一个其他字符 |
      | \s | 匹配任意一个空白字符 |
      | \S | 匹配除空白字符以外的任意一个其他字符 | import re
      pattern="\w\dpython\w"
      string="abcdfphp345python_py"
      result1=re.search(pattern,string)
      print(result1)
    • 原子表
      定义一组地位平等的原子,然后匹配的时候会取该原子表中的任意一个原子匹配,在Python中,原子表有[]表示比如[xyz]就是一个原子表,这个原子表中定义了3个原子,这3个原子的地位平等,如,我们定义的正则表达式为“[xyz]py”,对应的原字符串是"xpython",如果此时使用re.search()函数进行匹配,就可以匹配出结果"xpy",因为此时只要py前一位是x y z字母中的其中一个字母,就可以匹配成功。
      类似的,[^]代表的是除了中括号里面的原子均可以匹配,比如"[^xyz]py"能匹配"apy",但是却不能匹配"xpy"等。
      import re
      pattern1="\w\dpython[xyz]\w"
      pattern2="\w\dpython[^xyz]\w"
      pattern3="\w\dpython[xyz]\W"
      string="abcdfphp345pythony_py"
      result1=re.search(pattern1,string)
      result2=re.search(pattern2,string)
      result3=re.search(pattern3,string)
      print(result1)
      print(result2)
      print(result3)
  2. 元字符
    所谓元字符,就是正则表达式中具有一些特殊含义的字符,比如重复N次前面的字符等。 | 符号 | 含义 |
    | . | 匹配除换行符以外的任意字符 |
    | ^ | 匹配字符串的开始位置 |
    | $ | 匹配字符串的结束位置 |
    | * | 匹配0次、1次或多次前面的原子 |
    | ? | 匹配0次或1次前面的院子 |
    | + | 匹配1次或多次前面的原子 |
    | {n} | 前面的院子恰好出现n次 |
    | {n,} | 前面的原子至少出现n次 |
    | {n,m} | 前面的原子至少出现n次,至多出现m次 |
    | ‘|‘ | 模式选择符 |
    | () | 模式单元符 |
    具体来说元字符可以分为:任意匹配元字符、边界限制元字符、限定符、模式选择符、模式单元等。 <<<<<<< HEAD
    • 任意匹配元字符
      首先讲解任意匹配元字符 “.”,我们可以使用"."匹配一个除换行符以外的任意字符。比如,我们可以使用正则表达式".python..."匹配一个"python"字符前1位,后面有3位的格式的字符,这里的前一位和后面的3位可以是除了换行符以外的任意字符。import re pattern=".python..."string="abcdfphp345pythony_py"result1=re.search(pattern,string)print(result1)
    • 边界限制元字符
      可以使用"^"匹配字符串的开始,使用"$"匹配字符串的结束import re
      pattern1="^abd"
      pattern2="^abc"
      pattern3="py$"
      pattern4="ay$"
      string="abcdfphp345pythony_py"
      result1=re.search(pattern1,string)
      result2=re.search(pattern2,string)
      result3=re.search(pattern3,string)
      result4=re.search(pattern4,string)
      print(result1)
      print(result2)
      print(result3)
      print(result4)
    • 限定符
      常见的限定符包括*、?、+、{n}、{n,}、{n,m}.
      import re
      pattern1="py.*n"
      pattern2="cd{2}"
      pattern3="cd{3}"
      pattern4="cd{2,}"
      string="abcdddfphp345pythony_py"
      result1=re.search(pattern1,string)
      result2=re.search(pattern2,string)
      result3=re.search(pattern3,string)
      result4=re.search(pattern4,string)
      print(result1)
      print(result2)
      print(result3)
      print(result4)
    • 模式选择符
      模式选择符“|”,可以设置多个模式,匹配时,可以从中选择任意一个模式匹配。比如正则表达式“python|php”中,字符串“python”和"php"均满足匹配条件。import re
      pattern="python|php"
      string="abcdfphp345pythony_py"
      result1=re.search(pattern,string)
      print(result1)
    • 模式单元符
      模式单元符"()",可以将一些原子组合成一个大原子,小括号括起来的部分作为一个整体去使用。 import re
      pattern1="(cd){1,}"
      pattern2="cd{1,}"
      string="abcdcdcdcdfphp345pythony_py"
      result1=re.search(pattern1,string)
      result2=re.search(pattern2,string)
      print(result1)
      print(result2)
  3. 模式修正
    所谓模式修正符,即可以在不改变正则表达式的情况下,通过模式修正符改变正则表达式的含义,从而实现一些匹配结果的调整等功能。比如,可以使用模式修正符I让对于模块在匹配时不区分大小写。
    | 符号 | 含义 || I | 匹配时忽略大小写 |
    | M | 多行匹配 |
    | L | 做本地化识别匹配 |
    | U | 根据Unicode字符及解析字符 |
    | S | 让.匹配包括换行符,即用了该模块修正后,"."匹配就可以匹配任意的字符了|
    import re
    pattern1="python"
    pattern2="python"
    string="abcdfphp34Pythony_py"
    result1=re.search(pattern1,string)
    result2=re.search(pattern2,string,re.I)
    print(result1)
    print(result2)
  4. 贪婪模式与懒惰模式
    贪婪模式的核心点就是尽可能多地匹配,而懒惰模式的核心点就是尽可能少的匹配。
    import re
    pattern1="p.*y"#贪婪模式
    pattern2="p.*?y"#懒惰模式
    string="abcdfphp345pythony_py"
    result1=re.search(pattern1,string)
    result2=re.search(pattern2,string)
    print(result1)
    print(result2)

正则表达式常见函数

  1. re.match()函数
    如果想要从起始位置匹配一个模式,可以使用re.match()函数,格式
    re.match(pattern,string,flag)
    第一个参数为正则表达式,第二个参数源字符串,第三个是可选参数,代表标志位。
    import re
    string="apythonhellomypythonhispythonourpythonend"
    pattern=".python."
    result=re.match(pattern,string)
    result2=re.match(pattern,string).span()
    print(result)
    print(result2)
  2. re.search()函数
    re.search()函数会在全文中进行检索并匹配.
    import re
    string="hellomypythonhispythonourpythonend"
    pattern=".python."
    result=re.match(pattern,string)
    result2=re.search(pattern,string)
    print(result)
    print(result2)
  3. 全局匹配函数
    匹配一串字符串中多个结果。
    • 使用re.compile()对正则表达式进行预编译.
    • 编译后,使用findall()根据正则表达式从源字符串中将匹配的结果全部找出。 、import re
      string="hellomypythonhispythonourpythonend"
      pattern=re.compile(".python.")#预编译
      result=pattern.findall(string)#找出符合模式的所有结果
      print(result)

      import re
      string="hellomypythonhistpythonourpythonend"
      pattern=".python."
      result=re.compile(pattern).findall(string)
      print(result)
  4. re.sub函数
    使用正则表达式替换某些字符串功能,可以使用re.sub()函数实现。
    re.sub(pattern,rep,string,max)
    第一个参数为正则表达式,第二个参数为要替换成的字符串,第三个参数为源字符串,第四个参数为可选项,代表最多替换的次数,不写的话,就全部替换。
    import re
    string="hellomypytonhispythonourpythonend"
    pattern="python."
    result1=re.sub(pattern,"php",string)#全部替换
    result2=re.sub(pattern,"php",string,2)#最多替换两次
    print(result1)
    print(result2)

常见实例解析

  • 匹配.com或.cn后缀的URL网址
    import re
    pattern="[a-zA-Z]+://[^\s]*[.com|.cn]"
    string="<a href=‘http://www.baidu.com‘>百度首页</a>"
    result=re.search(pattern,string)
    print(result)
  • 匹配电话号码
    import re
    pattern="\d{4}-\d{7}|\d{3}-\d{8}"匹配电话号码的正则表达式
    string="0216728263682382265236"
    result=re.search(pattern,string)
    print(result)
  • 匹配电子邮件地址
    import re
    pattern="\w+([.+-]\w+)*@\w+([.-]\w+)*\.\w+([.-]\w+)*"#匹配电子邮箱的正则表达式
    string="<a href=‘http://www.baidu.com‘>百度首页</a><br><a href=‘mailto:[email protected]‘>电子邮箱地址</a>"
    result=re.search(pattern,string)
    print(result)

什么是Cookie

Http是一个无状态协议,即无法维持会话之间的状态。Cookie可以保存状态。

Cookiejar实战

import urllib.request
import urllib.parse
import http.cookiejar
url="post请求地址"
postdata=urllib.parse.urlencode({
"username":"用户名"
"password":"密码"
}).encode("utf-8")
req=urllib.request.Request(url,postdata)
req.add_header(‘User-Agent‘,‘User-Agent的值‘)
cjar=http.cookieJar.CookieJar() #使用http.cookiejar.CookieJar()创建CookieJar对象
opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cjar))#使用HTTPCookieProcessor创建cookie处理器,并以其为参数构建opener对象
urllib.request.install_opener(opener) #将opener安装为全局
file=opener.open(req)
data=file.read()
file=open("文件存储地址","wb")
file.write(data)
file.close()
url2="网页地址"
data2=urllib.request.urlopen(url2).read()
fh=open("文件地址",‘wb‘)
fh.write(data2)
fh.close()

=======

3f577ee4216aa3d991983f31467a7d7578dd9797

原文地址:https://www.cnblogs.com/dcotorbool/p/8279066.html

时间: 2024-08-19 05:11:21

python爬虫学习第五章正则的相关文章

python爬虫学习第四章

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption

python爬虫学习第三章

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption

Python爬虫学习系列教程

Python爬虫学习系列教程 大家好哈,我呢最近在学习Python爬虫,感觉非常有意思,真的让生活可以方便很多.学习过程中我把一些学习的笔记总结下来,还记录了一些自己实际写的一些小爬虫,在这里跟大家一同分享,希望对Python爬虫感兴趣的童鞋有帮助,如果有机会期待与大家的交流. Python版本:2.7 一.爬虫入门 1. Python爬虫入门一之综述 2. Python爬虫入门二之爬虫基础了解 3. Python爬虫入门三之Urllib库的基本使用 4. Python爬虫入门四之Urllib库

Python爬虫学习路线,强烈建议收藏这十一条

(一)如何学习Python 学习Python大致可以分为以下几个阶段: 1.刚上手的时候肯定是先过一遍Python最基本的知识,比如说:变量.数据结构.语法等,基础过的很快,基本上1~2周时间就能过完了,我当时是在这儿看的基础:Python 简介 | 菜鸟教程 2.看完基础后,就是做一些小项目巩固基础,比方说:做一个终端计算器,如果实在找不到什么练手项目,可以在 Codecademy - learn to code, interactively, for free 上面进行练习. 如果时间充裕的

swift学习第五章-字典的使用

//下面是关于字典的 //字典的格式[key:value] //字典可以存放基本类型和对象类型的 //声明一个字典 var dictionary1=["key1":"鸭鸭","key2":"肉包"] var keyValueCount=dictionary1.count//获取这个字典里面键值对的个数 dictionary1["key1"]="鸡鸡"//改变对应健的值 //updateV

Python爬虫学习:四、headers和data的获取

之前在学习爬虫时,偶尔会遇到一些问题是有些网站需要登录后才能爬取内容,有的网站会识别是否是由浏览器发出的请求. 一.headers的获取 就以博客园的首页为例:http://www.cnblogs.com/ 打开网页,按下F12键,如下图所示: 点击下方标签中的Network,如下: 之后再点击下图所示位置: 找到红色下划线位置所示的标签并点击,在右边的显示内容中可以查看到所需要的headers信息. 一般只需要添加User-Agent这一信息就足够了,headers同样也是字典类型: user

python爬虫主要就是五个模块:爬虫启动入口模块,URL管理器存放已经爬虫的URL和待爬虫URL列表,html下载器,html解析器,html输出器 同时可以掌握到urllib2的使用、bs4(BeautifulSoup)页面解析器、re正则表达式、urlparse、python基础知识回顾(set集合操作)等相关内容。

本次python爬虫百步百科,里面详细分析了爬虫的步骤,对每一步代码都有详细的注释说明,可通过本案例掌握python爬虫的特点: 1.爬虫调度入口(crawler_main.py) # coding:utf-8from com.wenhy.crawler_baidu_baike import url_manager, html_downloader, html_parser, html_outputer print "爬虫百度百科调度入口" # 创建爬虫类class SpiderMai

[python核心编程] 第五章练习题

第五章 数字 5-2. 操作符,写一个函数,计算并返回两个数的乘积“整理的时候才看到我把题目看成两个数的和了” 5-3. 标准类型操作符.写一段脚本,输入一个测验成绩,根据下面的标准,输出他的评分成绩(A-F) A:90~100 B:80~89 C:70~79 D:60~69 F:<60 5-4. 取余.判断给定年份是否是闰年.使用下面的公式. 一个闰年后就是指他可以被4整除,但不能被100整除,或者它可以被400整除. [python核心编程] 第五章练习题,布布扣,bubuko.com

Python核心编程第五章习题

Python核心编程-第五章-习题 5.1  整形,讲讲Python普通整形与长整形的区别? Python的标准整形类型是最通用的数字类型.在大多数32位机器上,标准整形类型的取值范围是-2**32-2**32 - 1. Python的长整型类型能表达的数值仅仅与你的机器支持的(虚拟)内存大小有关,换句话说,Python能轻松表达很大的整数. 长整型类型是标准整形类型的超集,当程序需要使用比标准整形更大的整型时,可以使用长整型类型,在整型值后面添加L,表示这个为长整型,3.0版本已经统一称为为整