Python正则表达式基础

运用正则表达式所依赖的库

#这个库在Python 3中自带,如果没有可以通过pip install re进行安装
import re

在爬虫过程中,正则表达式可以在网页源代码中提取到有用的信息。

基础

基础1
全局匹配函数是用格式 re.compile(正则表达式).findall(源字符串)

普通字符正常匹配
\n匹配换行符
\t匹配制表符
\w匹配字母、数字、下划线
\W匹配除字母、数字、下划线
\d匹配十进制数字
\D匹配除十进制数字
\s匹配空白字符
\S匹配除空白字符
[ab89x]原子表,匹配ab89x中1的任意一个
[^ab68x]原子表,匹配除ab89x中1的任意一个

实例1

import re
string = 'csdnet'
pat = 'dn'
res = re.compile(pat).findall(string)
print(res[0])
#输出为['dn']

基础2

普通字符正常匹配
.匹配除换行符外任一个字符
^匹配开始位置
$匹配结束位置
*前一个字符出现0\1\多次
?前一个字符出现0\1次
+前一个字符出现1\多次
{n}前一个字符恰好出现n次
{n,}前一个字符至少出现n次
{n,m}前一个字符至少出现n次,至多出现m次
()模式单元,通俗来说想提取出什么内容,就在正则中用小括号将其括起来

实例2

import re
string = 'editorcsdnnet'
pat = 'dn...'
res = re.compile(pat).findall(string)
print(res[0])
#输出结果为['dnnet']

基础3
贪婪模式:尽可能多地匹配
懒惰模式:尽可能少地匹配,精准模式
默认贪婪模式
如果出现下列组合,则代表懒惰模式:*? +?
实例3

import re
string = 'editorcsdnnet'
pat = 'd.*?t'
res = re.compile(pat).findall(string)
print(res)
#输出结果为['dit', 'dnnet']   懒惰模式,精准匹配

基础4
模式修正符,在不改变正则表达式的情况下通过模式修正符使匹配结果发生改变

普通字符正常匹配
re.S让.也可以匹配多行
re.l(大写的 i )让匹配时忽略大小写

实例4

import re
string = 'editoRcsDnnet'
pat = 'rcs'
res = re.compile(pat,re.I).findall(string)
print(res)
#输出结果为['Rcs']
import re
string = """edito
Rcs
dnne"""
pat = 'e.*e'
res = re.compile(pat,re.S).findall(string)
print(res)
#输出结果为['edito\nRcs\ndnne']

下面附加一个实例:

#利用正则表达式和requests获取前程无忧的职位信息
#下面是完整代码
#_*_coding:utf-8_*_
#作者:i7366464
#时间:2020/2/24 13:43
#文件:爬取前程无忧.py
#IDE :PyCharm
#https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud这个网站是下载Python第三方库的网站
import requests
import re
hd = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
}
city = input("请输入城市拼音:")#注意这里一定是拼音小写的,网站限制。。
job = input("请输入职位:")
txt = requests.get("https://www.51job.com/"+city)#所输入城市的前程无忧主页
data = bytes(txt.text,txt.encoding).decode("gbk","ignore")
pat_city_id= '<input type="hidden".*?id="jobarea".*?value="(.*?)"/>'
city_id = re.compile(pat_city_id,re.S).findall(data)[0]#获取到所输入城市的id
#print(city_id)
txt_1= requests.get("https://search.51job.com/list/"+str(city_id)+",000000,0000,00,9,99,"+job+",2,1.html?lang=c&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0",headers = hd)
data= bytes(txt_1.text,txt_1.encoding).decode("gbk","ignore")
#print(data)
pat = ' <div class="rt">.*?共(.*?)条职位.*?</div>'
num = re.compile(pat,re.S).findall(data)[0]#获取所搜索职位一共有多少
#print(num)
page = int(num)//50+1#算一下一共有多少页
#print(page)
for i in range(0,page):
    print("----正在爬"+str(i+1)+"页----")
    this_url = ("https://search.51job.com/list/"+str(city_id)+",000000,0000,00,9,99,"+job+",2,"+str(i+1)+".html?lang=c&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0")
    txt_2 = requests.get(this_url,headers = hd)
    data = bytes(txt_2.text,txt_2.encoding).decode("gbk","ignore")
#    print(data)
    pat_title = ' <span>.*?<a target="_blank" title="(.*?)" .*?</span>'
    pat_company = '<span class="t2"><a target="_blank" title="(.*?)" .*?</span>'
    pat_money = '<div class="el">.*?<span class="t4">(.*?)</span>.*?</div>'
    try:
        for j in range(0,50):
            title = re.compile(pat_title,re.S).findall(data)[j]#获取职位
            company = re.compile(pat_company,re.S).findall(data)[j]#获取公司
            money = re.compile(pat_money,re.S).findall(data)[j]#获取薪资
#            print(len(money))
#            print(title)
#            print(company)
#            print(money)
#            print("--------")
            with open("工作.doc","a+",encoding='utf-8')as f:
                f.write(title+"\r\n"+company+"\r\n"+money+"\r\n"+"------\r\n")

    except Exception as ess:
        pass

这个实例在另外一个博文中详细说明了,博文地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值