, content)
print(result)
print(result.group(1))
, content)
print(result)
print(result.group(1))
结果
4.贪婪匹配(.*?()):匹配尽可能多的结果
import re
content ='Hello 123 4567 wangyanling REDome'
result = re.match('^H.*?(d+).*?Dome
, content)
print(result)
print(result.group(1))
结果
以上3,4两个匹配方式请尽量采用非贪婪匹配
5.其他
换行:
import re
content ='''Hello 123 4567
wangyanling REDome'''
result = re.match('^H.*?(d+).*?Dome
, content,re.S)#re.S
print(result.group(1))
result = re.match('^H.*?(d+).*?Dome , content)
print(result.group(1))
结果:

转义字符:
import re
content = 'price is $5.00'
result = re.match('price is $5.00', content)
print(result)
result = re.match('price is $5.00', content)
print(result)
结果:
其中re.I使匹配对大小不敏感,re.S匹配包括换行符在内的所有字符,进行处理转义字符。匹配规则中有详细介绍。
1.2.2.re.search()
方法:
re.search(pattern, string, flags=0)#pattern:正则表达式(或者正则表达式对象)string:要匹配的字符串flags:修饰符
#re.match()和re.search()用法类似唯一的区别在于re.match()从字符串头开始匹配,若头匹配不成功,则返回None
对比一下与match()
import re
content ='Hello 123 4567 wangyanling REDome'
result = re.match('(d+)sd{4}sw{10}.*Dome, content)
print(result)#从开头开始查找,不能匹配返回None
result = re.search('(d+)sd{4}sw{10}.*Dome, content)
print(result)
print(result.group())
结果:
可以看出两个使用基本一致,search从头开始匹配,如果匹配不到就返回none.
1.2.3.re.findall()
方法: re.finditer(pattern, string, flags=0) # pattern:正则表达式(或者正则表达式对象)string:要匹配的字符串flags:修饰符
与re.search()类似区别在于re.findall()搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。找到 RE 匹配的所有子串,并把它们作为一个迭代器返回。
import re
html = '''
'''
regex_4='(.*?)'
results=re.findall(regex_4,html,re.S)
print(results)
for result in results:
print(result)
结果:
1.2.4.re.compile()
编译正则表达式模式,返回一个对象的模式。
方法: re.compile(pattern,flags=0) # pattern:正则表达式(或者正则表达式对象);flags:修饰符
看一个demo
import re
content ='Hello 123 4567 wangyanling REDome wangyanling 那小子很帅'
rr = re.compile(r'w*wangw*')
result =rr.findall(content)
print(result)
结果:
我们可以看出compile 我们可以把它理解为封装了一个公用的正则,类似于方法,然后功用。
1.2.5.其他
re.sub 替换字符
方法: re.sub(pattern, repl, string, count=0, flags=0) # pattern:正则表达式(或者正则表达式对象)repl:替换的字符串string:要匹配的字符串count:要替换的个数flags:修饰符
re.subn 替换次数
方法: re.subn(pattern, repl, string, count=0, flags=0) # pattern:正则表达式(或者正则表达式对象)repl:替换的字符串string:要匹配的字符串count:要替换的个数flags:修饰符
re.split()分隔字符
方法
re.split(pattern, string,[maxsplit])#正则表达式(或者正则表达式对象)string:要匹配的字符串;maxsplit:用于指定最大分割次数,不指定将全部分割

2.案例:爬取猫眼信息,写入txt,csv,下载图片
2.1.获取单页面信息
def get_one_page(html):
pattern= re.compile('
.*?board-index.*?>(d+).*?data-src="(.*?)".*?name">(.*?).*?star">(.*?).*?releasetime'
+ '.*?>(.*?).*?score.*?integer">(.*?).*?>(.*?).*?',re.S)#这里就用到了我们上述提到的一些知识点,非贪婪匹配,对象匹配,修饰符
items = re.findall(pattern,html)
for item in items:
yield {
'rank' :item[0],
'img': item[1],
'title':item[2],
'actor':item[3].strip()[3:] if len(item[3])>3 else '',
'time' :item[4].strip()[5:] if len(item[4])>5 else '',
'score':item[5] + item[6]
}
对于上面的信息我们可以看出是存到一个对象中那么接下来我们应该把它们存到文件当中去。
2.2.保存文件
我写了两种方式保存到txt和csv这些在python都有涉及html转义字符,不懂得可以去翻看一下。
2.2.1.保存到txt
def write_txtfile(content):
with open("Maoyan.txt",'a',encoding='utf-8') as f:
#要引入json,利用json.dumps()方法将字典序列化,存入中文要把ensure_ascii编码方式关掉
f.write(json.dumps(content,ensure_ascii=False) + "n")
f.close()
结果:

以上看到并非按顺序排列因为我用的是多线程。
2.2.2.保存到csv
def write_csvRows(content,fieldnames):
'''写入csv文件内容'''
with open("Maoyao.csv",'a',encoding='gb18030',newline='') as f:
#将字段名传给Dictwriter来初始化一个字典写入对象
writer = csv.DictWriter(f,fieldnames=fieldnames)
#调用writeheader方法写入字段名
writer.writerows(content)
f.close()
结果:
那么还有一部就是我们要把图片下载下来。
2.2.3.下载图片
def download_img(title,url):
r=requests.get(url)
with open(title+".jpg",'wb') as f:
f.write(r.content)

2.3.整体代码
这里面又到了多线程在这不在叙述后面会有相关介绍。这个demo仅做一案例,主要是对正则能有个认知。上面写的知识点有不足的地方望大家多多指教。
#抓取猫眼电影TOP100榜
from multiprocessing import Pool
from requests.exceptions import RequestException
import requests
import json
import time
import csv
import re
def get_one_page(url):
'''获取单页源码'''
try:
headers = {
"User-Agent":"Mozilla/5.0(WindowsNT6.3;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/68.0.3440.106Safari/537.36"
}
res = requests.get(url, headers=headers)
# 判断响应是否成功,若成功打印响应内容,否则返回None
if res.status_code == 200:
return res.text
return None
except RequestException:
return None
def parse_one_page(html):
'''解析单页源码'''
pattern = re.compile('
.*?board-index.*?>(d+).*?data-src="(.*?)".*?name">(.*?).*?star">(.*?).*?releasetime'
+ '.*?>(.*?).*?score.*?integer">(.*?).*?>(.*?).*?',re.S)
items = re.findall(pattern,html)
#采用遍历的方式提取信息
for item in items:
yield {
'rank' :item[0],
'img': item[1],
'title':item[2],
'actor':item[3].strip()[3:] if len(item[3])>3 else '', #判断是否大于3个字符
'time' :item[4].strip()[5:] if len(item[4])>5 else '',
'score':item[5] + item[6]
}
def write_txtfile(content):
with open("Maoyan.txt",'a',encoding='utf-8') as f:
#要引入json,利用json.dumps()方法将字典序列化,存入中文要把ensure_ascii编码方式关掉
f.write(json.dumps(content,ensure_ascii=False) + "n")
f.close()
def write_csvRows(content,fieldnames):
'''写入csv文件内容'''
with open("Maoyao.csv",'a',encoding='gb18030',newline='') as f:
#将字段名传给Dictwriter来初始化一个字典写入对象
writer = csv.DictWriter(f,fieldnames=fieldnames)
#调用writeheader方法写入字段名
#writer.writeheader() ###这里写入字段的话会造成在抓取多个时重复.
writer.writerows(content)
f.close()
def download_img(title,url):
r=requests.get(url)
with open(title+".jpg",'wb') as f:
f.write(r.content)
def main(offset):
fieldnames = ["rank","img", "title", "actor", "time", "score"]
url = "http://maoyan.com/board/4?offset={0}".format(offset)
html = get_one_page(url)
rows = []
for item in parse_one_page(html):
#download_img(item['rank']+item['title'],item['img'])
write_txtfile(item)
rows.append(item)
write_csvRows(rows,fieldnames)
if __name__ == '__main__':
pool = Pool()
#map方法会把每个元素当做函数的参数,创建一个个进程,在进程池中运行.
pool.map(main,[i*10 for i in range(10)])
有需要Python学习资料的小伙伴吗?小编整理【一套Python资料、源码和PDF】,感兴趣者可以关注小编后私信学习资料(是关注后私信哦)反正闲着也是闲着呢html转义字符,不如学点东西啦
限时特惠:本站每日持续更新海量设计资源,一年会员只需29.9元,全站资源免费下载
站长微信:ziyuanshu688
主题授权提示:请在后台主题设置-主题授权-激活主题的正版授权,授权购买:
RiTheme官网 声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。