zoukankan      html  css  js  c++  java
  • 正则表达式

    正则。 re
    正则表达式:
    . 除了换行符以外的任意字符
    w 数字。字母, 下划线
    d 数字
    s 空白符
     单词的末尾


    W 除了数字。字母, 下划线
    D 除了数字
    S 除了空白符
    ^ 字符串的开始
    $ 字符串的结束
    [] 字符组
    [^] 除了字符组外的内容

    * 0次或多次
    + 1次或多次
    ? 0次或1次
    {n} n次
    {n,m} n到m次
    {n,} n到无数次

    贪婪: +, *, ?
    惰性: .*?

    分组: ()
    python分组用来获取数据的

    re模块
    1. search() 搜索. 找到了就结束
    2. match() 匹配。 从头开始匹配
    3. findall() 匹配所有。 返回所有结果到列表
    4. finditer() 匹配所有。 返回迭代器
    group()获取数据

    re.split(正则, 字符串) 按照正则来切割字符串
    re.sub() 根据正则替换

    re.compile() 编译一段正则。 方便后面使用

    简单爬虫

    from urllib.request import urlopen
    import re

    # url = "https://www.dytt8.net/html/gndy/dyzz/20181114/57791.html"
    # content = urlopen(url).read().decode("gbk")
    # # print(content)
    #
    # obj = re.compile(r'<div id="Zoom">.*?译  名(?P<yiming>.*?)<br />◎片  名(?P<pianming>.*?)<br />◎年  '
    # r'代(?P<nian>.*?)<br />.*?<td style="WORD-WRAP: break-word" bgcolor="#fdfddf"><a href="(?P<url>.*?)">', re.S) # re.S 去掉.的换行
    #
    # res = obj.search(content)
    # print(res.group("yiming"))
    # print(res.group("pianming"))
    # print(res.group("nian"))
    # print(res.group("url"))

    obj = re.compile(r'<div class="item">.*?<spanclass="title">(?P<name>.*?)</span>.*?导演: (?P<daoyan>.*?)&nbsp;&nbsp;&nbsp;.*?<span class="rating_num" property="v:average">(?P<fen>.*?)</span>.*?<span>(?P<ren>.*?)人评价</span>', re.S)


    def getContent(url):
    content = urlopen(url).read().decode("utf-8")
    return content

    def parseContent(content):
    it = obj.finditer(content) # 把页面中所有匹配的内容进行匹配. 返回迭代器
    for el in it:
    yield {
    "name":el.group("name"),
    "daoyan":el.group("daoyan"),
    "ren":el.group("ren"),
    "fen":el.group("fen")
    }

    for i in range(10):
    url = "https://movie.douban.com/top250?start=%s&filter=" % i*25
    g = parseContent(getContent(url))
    f = open("movie.txt", mode="a", encoding="utf-8")
    for el in g:
    f.write(str(el)+" ")
    f.close()

  • 相关阅读:
    If you want the rainbow, you have to deal with the rain.
    Yesterday is history, tomorrow is a mystery, but today is a gift.
    .bashrc修改环境变量文件后ls之类的不能用了
    Flask项目中使用mysql数据库启动项目是发出警告
    flask 编码问题
    flask 密钥问题
    Flask 数据库连接
    查看cpu核的相关信息
    top命令常用
    gluster设置日志级别
  • 原文地址:https://www.cnblogs.com/wwjx/p/9997648.html
Copyright © 2011-2022 走看看