python正則怎么提取域名
問題描述
<script type='application/ld+json'>{ '@context': 'http://schema.org', '@type': 'SaleEvent', 'name': '10% Off First Orders', 'url': 'https://www.myvouchercodes.co.uk/coggles', 'image': 'https://mvp.tribesgds.com/dyn/oh/Ow/ohOwXIWglMg/_/mQR5xLX5go8/m0Ys/coggles-logo.png', 'startDate': '2017-02-17', 'endDate': '2017-12-31', 'location': {'@type': 'Place','name': 'Coggles','url': 'coggles.co.uk','address': 'Coggles' }, 'description': 'Get the top branded fashion items from Coggles at discounted prices. Apply this code and enjoy savings on your purchase.', 'eventStatus': 'EventScheduled'}</script>
怎么用python正則從這段腳本中提取coggles.co.uk域名呢,望各路高手指點顯示下身手...
問題解答
回答1:正則實現(xiàn)的話只要保證你的標(biāo)定/特征是唯一的就好。但是'url'這個標(biāo)志又不是唯一的。這個時候@prolifes的方法是很好的。
如果一定要正則實現(xiàn)呢,要用到零寬斷言(zero-width assertions),當(dāng)然這個詞的翻譯比較直,帶來很多誤解。它其實意思是指定位置的匹配,位置的寬度就是0嘛。
這里我們可以看到我們所需的這個'url'在'location'里面,可以以此為位置信息。
代碼如下:
re.search(’(?<=location).+?'url': '([^']+)'’, string, re.DOTALL).group(1)
稍微解釋一下,(?<=location)這個地方就是指前面得有l(wèi)ocation。后面有的話這樣寫:(?=location)re.DOTALL這個是必須的,因為這些字符串已經(jīng)跨行了。他的作用是將.的字符串匹配范圍擴大,包含換行符。'([^']+)'這個地方是我的習(xí)慣,[^']意指所有非'的字符,這就匹配了雙引號中所有的字符串。
回答2:這是一段挺標(biāo)準(zhǔn)的json,粗暴一點,直接轉(zhuǎn)換成json
import jsonstr = ’’’<script type='application/ld+json'>{ '@context': 'http://schema.org', '@type': 'SaleEvent', 'name': '10% Off First Orders', 'url': 'https://www.myvouchercodes.co.uk/coggles', 'image': 'https://mvp.tribesgds.com/dyn/oh/Ow/ohOwXIWglMg/_/mQR5xLX5go8/m0Ys/coggles-logo.png', 'startDate': '2017-02-17', 'endDate': '2017-12-31', 'location': {'@type': 'Place','name': 'Coggles','url': 'coggles.co.uk','address': 'Coggles' }, 'description': 'Get the top branded fashion items from Coggles at discounted prices. Apply this code and enjoy savings on your purchase.', 'eventStatus': 'EventScheduled'}</script>’’’d = json.loads(re.search(’({[sS]*})’, str).group(1))print d[’location’][’url’]
相關(guān)文章:
1. MySQL中無法修改字段名的疑問2. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?3. Matlab和Python編程相似嗎,有兩種都學(xué)過的人可以說說嗎4. 網(wǎng)頁爬蟲 - 用Python3的requests庫模擬登陸B(tài)ilibili總是提示驗證碼錯誤怎么辦?5. javascript - 微信小程序封裝定位問題(封裝異步并可能多次請求)6. android - QQ物聯(lián),視頻通話7. 請教各位大佬,瀏覽器點 提交實例為什么沒有反應(yīng)8. python的前景到底有大?如果不考慮數(shù)據(jù)挖掘,機器學(xué)習(xí)這塊?9. javascript - Web微信聊天輸入框解決方案10. mysql - 怎么讓 SELECT 1+null 等于 1
