• python 爬虫 杂七杂八


    ##sample 1 爬取中国日报新闻

    ##原文链接:https://blog.csdn.net/carson0408/article/details/89890687
    ##根据上图可以定义标题匹配规则,只打印括号内的内容 pattern3='<a href=".*?" target="_blank" title="(.*?)">'
    ###正则表达方式 https://www.jb51.net/article/65286.htm
    ##.+? 代表意思是所有非空字符
    ##正则表达式”ab*”如果用于查找”abbbc”,将找到”abbb”。而如果使用非贪婪的数量 词”ab*?”,将找到”a”。
    #[a-zA-Z_] 代表字符串,[0-9] 大表数字,[/hpl] 代表着特定字符/或者h或者p或者l
    #UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xd3 in position 252” please refer
    ##https://blog.csdn.net/u012767761/article/details/119836555
    ##从中国日报抓取英文新闻

    import re
    import urllib.request


    def getcontent(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0(Windows NT 10.0;Win64;x64;rv:66.0)Gecko/20100101 Firefox/66.0')
    data = urllib.request.urlopen(req).read().decode('utf-8')
    #print(data)
    #data = urllib.request.urlopen(req).read().decode('gbk')
    pattern1 = '<a href="/(.*?)" target="_blank" title=".*?">'
    urlList = re.compile(pattern1).findall(data)
    ##only some pattenn print bbs title 只包括体育新闻
    pattern2 = '<a target="_blank" class="txt1" shape="rect" href="/.*?">.*?</a>'
    # only some pattenn print bbs title 不包括体育新闻
    #pattern3 = '<a href=".*?" target="_blank" title=(.*?)>'
    #pattern3 = '<a href=".*?" tip="标题: <strong>.*?</strong>'
    #pattern3 = 'tip="标题: <strong>.*?</strong>'
    #pattern3 ='.*<a target="_blank" shape="rect" href="//.*?">[a-zA-Z_].*?</a>'
    #pattern3 = '<[/hpl].*?><a target="_blank" shape="rect" href="//.*?">[a-zA-Z_].*?</a>'
    #pattern3 = '<[/hpl].*?><a target="_blank".*? shape="rect" href="//.*?">[a-zA-Z_].*?</a>'
    pattern3 = '<[/hpl].*?><a target="_blank".*? shape="rect" href="//.*?">[a-zA-Z_].*?</a>'
    #pattern3 = '<[/hpl].+?><a target="_blank".+? shape="rect" href="//.*?">[a-zA-Z_].*?</a>'
    #pattern3 = '<[/hpl].*?><a target="_blank" shape="rect" href="//.*?">[a-zA-Z_].*?</a>'
    sourceList = re.compile(pattern2).findall(data)
    titleList = re.compile(pattern3).findall(data)
    #print (titleList)
    print(sourceList)
    authorList = []
    totalUrlList = []
    timeList = []
    info = []
    for url in urlList:
    url = "https://bbs.hupu.com/" + url
    totalUrlList.append(url)
    html = urllib.request.urlopen(url).read().decode('utf-8')
    pattern = '<a class="u" target="_blank" href=".*?">(.*?)</a>'
    pattern4 = '<span class="stime">(.*?)</span>'
    aulist = re.compile(pattern).findall(html)
    tiList = re.compile(pattern4).findall(html)
    authorList.append(aulist[0])
    timeList.append(tiList[0])
    #info.append(totalUrlList)
    info.append(sourceList)
    info.append(titleList)
    # info.append(authorList)
    # info.append(timeList)
    return info


    if __name__ == '__main__':
    url = "http://www.chinadaily.com.cn/"
    info = getcontent(url)
    #print(info[1])
    #print (info[0])
    print (len(info[1]))
    ##打印所有记录非体育的标题
    for i in range(0,len(info[1])):
    #print (info[1][i])
    #只打印链接和标题
    text=info[1][i]
    start = text.find("href")
    print (text[start+1:-4])
    # for i in info[1]:
    # prin i
    #print(len(info))
    # totalurlList = info[0]
    # sourceList = info[1]
    titleList = info[0]
    # authorList = info[3]
    # timeList = info[4]
    #length = len(totalurlList)
    length = len(titleList)
    ##打印体育的标题
    for i in range(0,length):
    #print (info[1][i])
    #只打印链接和标题
    text=info[0][i]
    start = text.find("href")
    print (text[start+1:-4])
    # for i in info[1]:
    # for i in range(length):
    # str = "标题:" + titleList[i] + " "
    # # str = "标题:" + titleList[i] + " " + "作者:" + authorList[i] + " " + "URL:" + totalurlList[i] + " " + "发布时间:" + \
    # # timeList[i] + " " + "帖子来源:" + sourceList[i]
    # print(str)




    ###sample 2
    get 60oldbbs  数据
    ##原文链接:https://blog.csdn.net/carson0408/article/details/89890687
    ##根据上图可以定义标题匹配规则, pattern3='<a href=".*?" target="_blank" title="(.*?)">'
    ###正则表达方式 https://www.jb51.net/article/65286.htm
    ##.+? 代表意思是所有非空字符
    ##正则表达式”ab*”如果用于查找”abbbc”,将找到”abbb”。而如果使用非贪婪的数量 词”ab*?”,将找到”a”。
    #UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xd3 in position 252” please refer
    ##https://blog.csdn.net/u012767761/article/details/119836555
    #get 60oldbbs 数据
    import re
    import urllib.request


    def getcontent(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0(Windows NT 10.0;Win64;x64;rv:66.0)Gecko/20100101 Firefox/66.0')
    #data = urllib.request.urlopen(req).read().decode('utf-8')
    data = urllib.request.urlopen(req).read().decode('gbk')
    pattern1 = '<a href="/(.*?)" target="_blank" title=".*?">'
    urlList = re.compile(pattern1).findall(data)
    pattern2 = '<a href="/.+?" target="_blank">(.*?)</a>'
    # only print bbs title
    #pattern3 = '<a href=".*?" target="_blank" title=(.*?)>'
    #pattern3 = '<a href=".*?" tip="标题: <strong>.*?</strong>'
    pattern3 = 'tip="标题: <strong>.*?</strong>'
    sourceList = re.compile(pattern2).findall(data)
    titleList = re.compile(pattern3).findall(data)
    #print (titleList)
    authorList = []
    totalUrlList = []
    timeList = []
    info = []
    for url in urlList:
    url = "https://bbs.hupu.com/" + url
    totalUrlList.append(url)
    html = urllib.request.urlopen(url).read().decode('utf-8')
    pattern = '<a class="u" target="_blank" href=".*?">(.*?)</a>'
    pattern4 = '<span class="stime">(.*?)</span>'
    aulist = re.compile(pattern).findall(html)
    tiList = re.compile(pattern4).findall(html)
    authorList.append(aulist[0])
    timeList.append(tiList[0])
    info.append(totalUrlList)
    # info.append(sourceList)
    info.append(titleList)
    # info.append(authorList)
    # info.append(timeList)
    return info


    if __name__ == '__main__':
    url = "http://www.60old.cn/forum.php"
    info = getcontent(url)
    print(info[0])
    print (len(info[0]))
    ##只取前10条记录
    for i in range(0,10):
    print (info[1][i])
    # for i in info[1]:
    # prin i
    #print(len(info))
    # totalurlList = info[0]
    # sourceList = info[1]
    titleList = info[0]
    # authorList = info[3]
    # timeList = info[4]
    #length = len(totalurlList)
    length = len(titleList)
    for i in range(length):
    str = "标题:" + titleList[i] + " "
    # str = "标题:" + titleList[i] + " " + "作者:" + authorList[i] + " " + "URL:" + totalurlList[i] + " " + "发布时间:" + \
    # timeList[i] + " " + "帖子来源:" + sourceList[i]
    print(str)


    ###sample 3 从虎扑nba 抓取数据

    ##原文链接:https://blog.csdn.net/carson0408/article/details/89890687
    ##根据上图可以定义标题匹配规则, pattern3='<a href=".*?" target="_blank" title="(.*?)">'
    ###正则表达方式 https://www.jb51.net/article/65286.htm
    ##.+? 代表意思是所有非空字符
    ##正则表达式”ab*”如果用于查找”abbbc”,将找到”abbb”。而如果使用非贪婪的数量 词”ab*?”,将找到”a”。
    ##get 虎扑nba 数据
    import re
    import urllib.request


    def getcontent(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent', 'Mozilla/5.0(Windows NT 10.0;Win64;x64;rv:66.0)Gecko/20100101 Firefox/66.0')
    data = urllib.request.urlopen(req).read().decode('utf-8')
    pattern1 = '<a href="/(.*?)" target="_blank" title=".*?">'
    urlList = re.compile(pattern1).findall(data)
    pattern2 = '<a href="/.+?" target="_blank">(.*?)</a>'
    ##only print bbs title
    #pattern3 = '<a href=".*?" target="_blank" title=(.*?)>'
    pattern3 ='<span class="t-title">(.*?)</span>'
    sourceList = re.compile(pattern2).findall(data)
    titleList = re.compile(pattern3).findall(data)
    #print (titleList)
    authorList = []
    totalUrlList = []
    timeList = []
    info = []
    for url in urlList:
    url = "https://bbs.hupu.com/" + url
    totalUrlList.append(url)
    html = urllib.request.urlopen(url).read().decode('utf-8')
    pattern = '<a class="u" target="_blank" href=".*?">(.*?)</a>'
    pattern4 = '<span class="stime">(.*?)</span>'
    aulist = re.compile(pattern).findall(html)
    tiList = re.compile(pattern4).findall(html)
    authorList.append(aulist[0])
    timeList.append(tiList[0])
    info.append(totalUrlList)
    # info.append(sourceList)
    info.append(titleList)
    # info.append(authorList)
    # info.append(timeList)
    return info


    if __name__ == '__main__':
    url = "https://bbs.hupu.com/all-nba"
    info = getcontent(url)
    #print(info[1])
    #print (len(info[1]))
    for i in range(0,len(info[1])):
    print (info[1][i])
    # for i in info[1]:
    # prin i
    #print(len(info))
    # totalurlList = info[0]
    # sourceList = info[1]
    titleList = info[0]
    # authorList = info[3]
    # timeList = info[4]
    #length = len(totalurlList)
    length = len(titleList)
    for i in range(length):
    str = "标题:" + titleList[i] + " "
    # str = "标题:" + titleList[i] + " " + "作者:" + authorList[i] + " " + "URL:" + totalurlList[i] + " " + "发布时间:" + \
    # timeList[i] + " " + "帖子来源:" + sourceList[i]
    print(str)


    ###sample 4 正则算法贪婪算法和非贪婪算法 和带括号的打印

    ###正则算法贪婪算法和非贪婪算法
    #https://docs.python.org/zh-cn/3/library/re.html
    #https://blog.csdn.net/m0_37852369/article/details/79101892
    import re

    example = "<div>test1</div><div>test2</div>"

    ##贪婪算法会从最开始的标注符找,一直找,直到找到最后一个标识符
    greedPattern = re.compile("<div>.*</div>")
    #print(greedPattern)
    ##非贪婪算法会从最开始的标注符找,找到最后一个标识符第一个就中止

    #notGreedPattern = re.compile("<div>.*?</div>")
    notGreedPattern = re.compile("<div>.+?</div>")


    greedResult = greedPattern.search(example)
    notGreedResult = notGreedPattern.search(example)

    print("greedResult = %s" % greedResult)
    print("notGreedResult = %s" % notGreedResult)



    #######和带括号的打印

    data="<a target=\"_blank\" shape=\"rect\" href=\"//www.chinadaily.com.cn/a/202202/23/WS62156e5da310cdd39bc88468.html\">E-commerce boosts rural development</a>"

    ##不带括号的,打印一行的所有
    pattern1 = '<a target="_blank".*? shape="rect" href="//.*?">[a-zA-Z_].*?</a>'

    #result
    #['<a target="_blank" shape="rect" href="//www.chinadaily.com.cn/a/202202/23/WS62156e5da310cdd39bc88468.html">E-commerce boosts rural development</a>']

    ##带括号的只打印括号里的匹配
    pattern3 = '<a target="_blank".*? shape="rect" href="//.*?">([a-zA-Z_].*?)</a>'
    #result
    #['E-commerce boosts rural development']

    pattern2 = '<a target="_blank" shape="rect" href="/.*?">(.*?)</a>'
    #result
    #['E-commerce boosts rural development']

    ##验证
    titleList1 = re.compile(pattern1).findall(data)
    print(titleList1)

    titleList3 = re.compile(pattern3).findall(data)
    print(titleList3)
    titleList2 = re.compile(pattern2).findall(data)
    print(titleList2)


    ###sample 5
    https://docs.python.org/zh-cn/3/library/re.html

    正则表达式操作



    re --- 正则表达式操作

    源代码: Lib/re.py


    本模块提供了与 Perl 语言类似的正则表达式匹配操作。

    模式和被搜索的字符串既可以是 Unicode 字符串 (str) ,也可以是8位字节串 (bytes)。 但是,Unicode 字符串与 8 位字节串不能混用:也就是说,不能用字节串模式匹配 Unicode 字符串,反之亦然;同理,替换操作时,替换字符串的类型也必须与所用的模式和搜索字符串的类型一致。

    正则表达式用反斜杠字符 ('\') 表示特殊形式,或是允许在使用特殊字符时,不引发它们的特殊含义。 这与 Python 的字符串字面值中对相同字符出于相同目的的用法产生冲突;例如,要匹配一个反斜杠字面值,用户可能必须写成 '\\\\' 来作为模式字符串,因为正则表达式必须为 \\,而每个反斜杠在普通 Python 字符串字面值中又必须表示为 \\。 而且还要注意,在 Python 的字符串字面值中使用的反斜杠如果有任何无效的转义序列,现在会触发 DeprecationWarning,但以后会改为 SyntaxError。 此行为即使对于正则表达式来说有效的转义字符同样会发生。

    解决办法是对于正则表达式样式使用 Python 的原始字符串表示法;在带有 'r' 前缀的字符串字面值中,反斜杠不必做任何特殊处理。 因此 r"\n" 表示包含 '\' 和 'n' 两个字符的字符串,而 "\n" 则表示只包含一个换行符的字符串。 样式在 Python 代码中通常都使用原始字符串表示法。

    绝大多数正则表达式操作都提供为模块函数和方法,在 编译正则表达式. 这些函数是一个捷径,不需要先编译正则对象,但是损失了一些优化参数。

    参见

     

    第三方模块 regex , 提供了与标准库 re 模块兼容的 API 接口,同时,还提供了更多功能和更全面的 Unicode 支持。

    正则表达式语法

    正则表达式(或 RE)指定了一组与之匹配的字符串;模块内的函数可以检查某个字符串是否与给定的正则表达式匹配(或者正则表达式是否匹配到字符串,这两种说法含义相同)。

    正则表达式可以拼接;如果 A 和 B 都是正则表达式,则 AB 也是正则表达式。通常,如果字符串 p 匹配 A,并且另一个字符串 q 匹配 B,那么 pq 可以匹配 AB。除非 A 或者 B 包含低优先级操作,A 和 B 存在边界条件;或者命名组引用。所以,复杂表达式可以很容易的从这里描述的简单源语表达式构建。更多正则表达式理论和实现,详见 the Friedl book [Frie09] ,或者其他构建编译器的书籍。

    以下是正则表达式格式的简要说明。更详细的信息和演示,参考 正则表达式HOWTO

    正则表达式可以包含普通或者特殊字符。绝大部分普通字符,比如 'A''a', 或者 '0',都是最简单的正则表达式。它们就匹配自身。你可以拼接普通字符,所以 last 匹配字符串 'last'. (在这一节的其他部分,我们将用 this special style 这种方式表示正则表达式,通常不带引号,要匹配的字符串用 'in single quotes' ,单引号形式。)

    有些字符,比如 '|' 或者 '(',属于特殊字符。 特殊字符既可以表示它的普通含义, 也可以影响它旁边的正则表达式的解释。

    重复修饰符 (*+?{m,n}, 等) 不能直接嵌套。这样避免了非贪婪后缀 ? 修饰符,和其他实现中的修饰符产生的多义性。要应用一个内层重复嵌套,可以使用括号。 比如,表达式 (?:a{6})* 匹配6个 'a' 字符重复任意次数。

    特殊字符有:

    .

    (点) 在默认模式,匹配除了换行的任意字符。如果指定了标签 DOTALL ,它将匹配包括换行符的任意字符。

    ^

    (插入符号) 匹配字符串的开头, 并且在 MULTILINE 模式也匹配换行后的首个符号。

    $

    匹配字符串尾或者在字符串尾的换行符的前一个字符,在 MULTILINE 模式下也会匹配换行符之前的文本。 foo 匹配 'foo' 和 'foobar',但正则表达式 foo$ 只匹配 'foo'。 更有趣的是,在 'foo1\nfoo2\n' 中搜索 foo.$,通常匹配 'foo2',但在 MULTILINE 模式下可以匹配到 'foo1';在 'foo\n' 中搜索 $ 会找到两个(空的)匹配:一个在换行符之前,一个在字符串的末尾。

    *

    对它前面的正则式匹配0到任意次重复, 尽量多的匹配字符串。 ab* 会匹配 'a''ab',或者 'a' 后面跟随任意个 'b'

    +

    对它前面的正则式匹配1到任意次重复。 ab+ 会匹配 'a' 后面跟随1个以上到任意个 'b',它不会匹配 'a'

    ?

    对它前面的正则式匹配0到1次重复。 ab? 会匹配 'a' 或者 'ab'

    *?+???

    '*''+',和 '?' 修饰符都是 贪婪的;它们在字符串进行尽可能多的匹配。有时候并不需要这种行为。如果正则式 <.*> 希望找到 '<a> <c>',它将会匹配整个字符串,而不仅是 '<a>'。在修饰符之后添加 ? 将使样式以 非贪婪`方式或者 :dfn:`最小 方式进行匹配; 尽量  的字符将会被匹配。 使用正则式 <.*?> 将会仅仅匹配 '<a>'

    {m}

    对其之前的正则式指定匹配 m 个重复;少于 m 的话就会导致匹配失败。比如, a{6} 将匹配6个 'a' , 但是不能是5个。

    {m,n}

    对正则式进行 m 到 n 次匹配,在 m 和 n 之间取尽量多。 比如,a{3,5} 将匹配 3 到 5个 'a'。忽略 m 意为指定下界为0,忽略 n 指定上界为无限次。 比如 a{4,}b 将匹配 'aaaab' 或者1000个 'a' 尾随一个 'b',但不能匹配 'aaab'。逗号不能省略,否则无法辨别修饰符应该忽略哪个边界。

    {m,n}?

    前一个修饰符的非贪婪模式,只匹配尽量少的字符次数。比如,对于 'aaaaaa', a{3,5} 匹配 5个 'a' ,而 a{3,5}? 只匹配3个 'a'

    \

    转义特殊字符(允许你匹配 '*''?', 或者此类其他),或者表示一个特殊序列;特殊序列之后进行讨论。

    如果你没有使用原始字符串( r'raw' )来表达样式,要牢记Python也使用反斜杠作为转义序列;如果转义序列不被Python的分析器识别,反斜杠和字符才能出现在字符串中。如果Python可以识别这个序列,那么反斜杠就应该重复两次。这将导致理解障碍,所以高度推荐,就算是最简单的表达式,也要使用原始字符串。

    []

    用于表示一个字符集合。在一个集合中:

    • 字符可以单独列出,比如 [amk] 匹配 'a', 'm', 或者 'k'

    • 可以表示字符范围,通过用 '-' 将两个字符连起来。比如 [a-z] 将匹配任何小写ASCII字符, [0-5][0-9] 将匹配从 00 到 59 的两位数字, [0-9A-Fa-f] 将匹配任何十六进制数位。 如果 - 进行了转义 (比如 [a\-z])或者它的位置在首位或者末尾(如 [-a] 或 [a-]),它就只表示普通字符 '-'

    • 特殊字符在集合中,失去它的特殊含义。比如 [(+*)] 只会匹配这几个文法字符 '(''+''*', or ')'

    • 字符类如 \w 或者 \S (如下定义) 在集合内可以接受,它们可以匹配的字符由 ASCII 或者 LOCALE 模式决定。

    • 不在集合范围内的字符可以通过 取反 来进行匹配。如果集合首字符是 '^' ,所有  在集合内的字符将会被匹配,比如 [^5] 将匹配所有字符,除了 '5', [^^] 将匹配所有字符,除了 '^'^ 如果不在集合首位,就没有特殊含义。

    • 在集合内要匹配一个字符 ']',有两种方法,要么就在它之前加上反斜杠,要么就把它放到集合首位。比如, [()[\]{}] 和 []()[{}] 都可以匹配括号。

    • Unicode Technical Standard #18 里的嵌套集合和集合操作支持可能在未来添加。这将会改变语法,所以为了帮助这个改变,一个 FutureWarning 将会在有多义的情况里被 raise,包含以下几种情况,集合由 '[' 开始,或者包含下列字符序列 '--''&&''~~', 和 '||'。为了避免警告,需要将它们用反斜杠转义。

    在 3.7 版更改: 如果一个字符串构建的语义在未来会改变的话,一个 FutureWarning 会 raise 。

    |

    #######sample 6
    https://blog.csdn.net/m0_37852369/article/details/79101892

    三、原理分析
    在正则表达式中一般默认采用的是贪婪模式,在上面的例子当中已经匹配到了“ab”时已经可以使整个表达式匹配成功,但是由于采用的是贪婪模式,所以还需要往后继续匹配,检查时候存在更长的可以匹配成功的字符串。一直到匹配到最后一个”b”的时候,后面已经没有可以成功匹配的字符串了,匹配结束。返回匹配结果“abbbbbb”。
    所以,我们可以将贪婪模式理解为:在整个表达式匹配成功的前提下,尽可能多的匹配。

    非贪婪模式也就是将我们例子中的正则表达式“ab+”改为”ab+?”,当匹配到“ab”时,已经匹配成功,直接结束匹配,不在向后继续尝试,返回匹配成功的字符串”ab”。
    所以,我们可以将非贪婪模式理解为:在整个表达式匹配成功的前提下,尽可能少的匹配

    四、实例
    import re

    example = "<div>test1</div><div>test2</div>"

    greedPattern = re.compile("<div>.*</div>")
    notGreedPattern = re.compile("<div>.*?</div>")

    greedResult = greedPattern.search(example)
    notGreedResult = notGreedPattern.search(example)

    print("greedResult = %s" % greedResult.group())
    print("notGreedResult = %s" % notGreedResult.group())
    ————————————————
    版权声明:本文为CSDN博主「坚强的狗蛋」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/m0_37852369/article/details/79101892




  • 相关阅读:
    C++ map详解
    C++ vector和list的区别
    C++静态存储,动态存储
    C++文件输入和输出
    C/C++数组名与指针的区别详解
    C++运算符重载详解
    poj3177Redundant Paths tarjan缩点
    C++编译过程与内存空间
    [JAVA &#183; 0基础]:19.容器类
    FFmpeg总结(六)AV系列结构体之AVPacket
  • 原文地址:https://www.cnblogs.com/feiyun8616/p/15927797.html
Copyright © 2020-2023  润新知