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:正则实现的话只要保证你的标定/特征是唯一的就好。但是'url'这个标志又不是唯一的。这个时候@prolifes的方法是很好的。
如果一定要正则实现呢,要用到零宽断言(zero-width assertions),当然这个词的翻译比较直,带来很多误解。它其实意思是指定位置的匹配,位置的宽度就是0嘛。
这里我们可以看到我们所需的这个'url'在'location'里面,可以以此为位置信息。
代码如下:
re.search(’(?<=location).+?'url': '([^']+)'’, string, re.DOTALL).group(1)
稍微解释一下,(?<=location)这个地方就是指前面得有location。后面有的话这样写:(?=location)re.DOTALL这个是必须的,因为这些字符串已经跨行了。他的作用是将.的字符串匹配范围扩大,包含换行符。'([^']+)'这个地方是我的习惯,[^']意指所有非'的字符,这就匹配了双引号中所有的字符串。
回答2:这是一段挺标准的json,粗暴一点,直接转换成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’]
相关文章:
1. javascript - 关于禁用文本选择与复制的问题2. python - 用Mac自带的Apache服务器开发CGI,在浏览器直接输出纯文本了?求解3. javascript - vue 如何获取组件自身高度4. node.js - express框架,设置浏览器从缓存中读取静态文件,只有js从缓存中读取了,css还有一些图片为何没有从缓存中读取?5. 数据库 - Mysql的存储过程真的是个坑!求助下面的存储过程哪里错啦,实在是找不到哪里的问题了。6. 站点内容复制额外增加的版权申明,真的很反人类。试问产品自己在用这个站点吗?7. 图片上传成功但数据库字段是空8. javascript - js代码转python9. css3 - 求clearfix使用方法10. jquery - css3 scale 缩放图片问题

网公网安备