正则表达式实例

正则表达式实例

实例1:通过爬虫将网页中的skuid和skuimgurl截取出来

注意:网页的内容复制和爬虫下来的内容不一致(这里会出现很多空格),所以需要将pycharm爬下来的内容复制到网页上进行核对,如果将网页上的内容复制到http://regex101.com上匹配就会为空列表

re
requests

url = session=requests.session()
r=session.get(url)
html=r.text

reg=re.compile()
方式二:reg=re.compile(r"\"skuid\":\"(\d+)\",\s+.\s+\".\s+\"skuimgurl\":\"(\S+)\"")

(reg.findall(html)) #匹配正则中的()的内容,比如(\d+),(\S+)

实例2:

实现功能1:将upstream开头的内容加入到upstream的文本

实现功能2:将location开头的内容加入到location的文本

import codecs
import re
import os

regUpstream = re.compile(r"\s*(upstream\s+(\S+)\s+{[^}]+})")

with codecs.open("ga10.wms5.jd.com.txt") as fu:
    textList = regUpstream.findall(fu.read())
    if not os.path.exists("upstream"):      #判断upstream是否存在
        os.mkdir("upstream")                #创建
    os.chdir("upstream")                    #进入upstream里
    for item in textList:
        with codecs.open(item[1], "w") as fw:
            fw.write(item[0])
    os.chdir("..")                          #相当于cd ..,返回当前目录

regLocation = re.compile(r"(location\s+/(\S+)/\s+{\s+proxy_next_upstream.*[^]]*?})")
with codecs.open("ga10.wms5.jd.com.txt") as fl:
    textLocation = regLocation.findall(fl.read())
    if not os.path.exists("location"):
        os.mkdir("location")
    os.chdir("location")
    for each in textLocation:
        file = each[1] + ".locaion.conf"
        with codecs.open(file, "w") as flw:
            flw.write(each[0])

猜你喜欢

转载自blog.51cto.com/jacksoner/2112684