2018年5月3日筆記
阿新 • • 發佈:2018-05-05
表達 pst .text mkdir html str fin 字符串 文件 為匹配該模式的正則表達式
- 常用的正則表達式匹配規則
\d 表示一個數字字符,等價於 [0-9]
\D 表示一個非數字字符,等價於 [^\d]
\s 表示一個空白字符,等價於 [<空格>\t\r\n\f\v]
\S 表示一個非空白字符,等價於 [^\s]
\w 表示一個單詞字符(數字或字母),等價於 [A-Za-z0-9_]
\W 表示一個非單詞字符,等價於 [^\w]
. 匹配除換行符\n之外的任意一個字符
.* 在一行內,貪婪(盡可能多)匹配任意個字符
.*? 在一行內,非貪婪(盡可能少)匹配任意個字符
(?P<name>pattern) 和 (P=name) 用來多次匹配同一模式的字符串,pattern
- 習題1:(爬蟲)獲取網頁內容中的skuid字段和對應圖片
1 # 爬蟲:獲取網頁內容中的skuid字段和對應圖片 2 import re 3 import requests 4 5 url = "http://qwd.jd.com/fcgi-bin/qwd_searchitem_ex?skuid=26878432382%7C1658610413%7C26222795271%7C25168000024%7C11731514723%7C26348513019%7C20000220615%7C4813030%7C25965247088%7C5327182%7C19588651151%7C1780924%7C15495544751%7C10114188069%7C27036535156%7C10123099847%7C26016197600%7C10503200866%7C16675691362%7C15904713681" 6 7 session = request.session() 8 r = session.get(url) 9 html = r.text 10 11 reg = re.compile(r"\"skuid\":\"(\d+)\",\s+\"\S+\s+\"skuurl\"\S+\s+\"skuimgurl\":\"(\S+)\",") 12 result = reg.findall(html) 13 print(result)
- 習題2:將指定文件中的每個Upstream和Location都保存為一個文件
備註:先在regex101網站上,將相應的正則表達式寫正確,然後再寫python代碼
匹配upstream的正則表達式如下:
匹配location的正則表達式如下:
python代碼如下:
1 import codecs 2 import re 3 import os 4 5 regUpstream =re.compile(r"\s*(upstream\s+(\S+)\s+{[^}]+})") 6 with codecs.open("ga10.txt") as fu: 7 textUpstream = regUpstream.findall(fu.read()) 8 if not os.path.exists("upstream"): 9 os.mkdir("upstream") 10 os.chdir("upstream") 11 for item in textUpstream: 12 with codecs.open(item[1], "w") as fw: 13 fw.write(item[0]) 14 os.chdir("..") 15 16 17 regLocation = re.compile(r"\s*(location\s+/(\S+)/\s+{[^}]+})") 18 with codecs.open("ga10.txt") as fl: 19 textLocation = regLocation.findall(fl.read()) 20 if not os.path.exists("location"): 21 os.mkdir("location") 22 os.chdir("location") 23 for item in textLocation: 24 file = item[1] + ".location.conf" 25 with codecs.open(file, "w") as fw2: 26 fw2.write(item[0])
2018年5月3日筆記