您当前的位置: 首页 >  Python

Python爬虫:正则匹配网址中的数字

彭世瑜 发布时间:2018-05-26 09:44:09 ,浏览量:5


# 匹配网址中的数字
import re

url = "https://www.baidu.com/company/13828?param=abc"
com_id = re.match(".*company/(\d+)", url)

print com_id.group(1)
# 13828
将其封装为函数
# -*- coding: utf-8 -*-

# @File    : get_digit.py
# @Date    : 2018-05-25

# 匹配网址中的数字
import re

def get_digit(url, reg_exp=".*/(\d+)"):
    """匹配网址中的数字
    :param
        url{str}: 网址字符串
        reg_exp{str}: 正则匹配规则
    :return
        digit {None}/{str}: 空或者数字字符串
    """
    digit = None

    pattern = re.compile(reg_exp)
    result = pattern.match(url)

    if result:
        digit = result.group(1)

    return digit


if __name__ == '__main__':
    # 匹配为空
    url = ""
    ret = get_digit(url)
    print(ret)
    # None

    # 匹配一个
    url = "https://www.baidu.com/company/13828?param=abc"
    ret = get_digit(url)
    print(ret)
    # 13828

    # 匹配第一个
    url = "https://www.baidu.com/company/13828?param=234234"
    ret = get_digit(url)
    print(ret)
    # 13828
关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 5浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0461s