1. 程式人生 > >學習的一點爬蟲小例項

學習的一點爬蟲小例項

def function():
    pat="[a-zA-Z]+://[^\s]*[.com|.cn]"
    string='<a herf="http://www.baidu.com>haafdsg</a>'
    res=re.compile(pat).findall(string)
    print(res)


def function3():
    pat='<p class="fl">\w*(.*?)</p>'
    pat2='<span>(.*?)</span>'
    data=urllib.request.urlopen("http://edu.51cto.com/mic-position/420.html?source=wzq").read()
    data2=urllib.request.urlopen("http://www.boc.cn/bcservice/").read()
    result=re.compile(pat2).findall(str(data2,"utf-8"))
    print(result)
    #方法一:
    with open("./爬蟲練習.txt", "w+",encoding="utf-8") as f:
        f.write(str(result))
        f.close()

def function2():
    pat = "yue"
    string = "http:/yum.iqianyue.com"
    string2 = "fhajghajdgh"
    result1 = re.search(pat, string)
    res2 = re.search(pat, string2)
    print(result1)
    print(res2)
    pat2 = "\n"
    string3 = """aljgagghaskghka
        gkhasgkas"""
    res3 = re.search(pat2, string3)
    print(res3)
    # \w是通用字元   匹配的任意的一個字母、下劃線、數字
    # \d 匹配十進位制數
    # \s 匹配空白字元
    # \W 和匹配與小寫的相反的字元
    # \S
    pat4 = "\w\dpython\w"
    string4 = "ahgdhgaghasfjg8pythonhdsga;sdgdhgaus9pythonhdjvcxcjvbagdsfsa"
    res4 = re.search(pat4, string4)  # 只是進行了一次匹配
    print(res4)
    # 原子表定義一組平等的原子表示一個同等原子的地位
    pat5 = "pyth[jsz]n"
    string5 = "akgdhahgpythjsnaewurqpdvpythzn"
    print(re.search(pat5, string5))
    # 元字元就是正則表示式中一些具有特殊的含義的字元 比如重負N次前面的字元
    # 一點 匹配任意的字元 ^ 匹配字串的開始的位置 $ 用來匹配結束的意思
    # "s*"0 1 多次都可以匹配的
    # +匹配前面的一次和多次的原則
    # ?匹配1或者0次
    # {3}表示出現只有三次 t{6}6個t連續出現的次數 t{n,}至少出現的n次數t{4,7}出現的至少4次最多7次
    # | 模式選擇符 或者    ()用於提取某一個內容上面
    pat6 = "python....."  # 表示除了換行符都可以進行匹配
    string6 = "hgahgapythongapgpre"
    res6 = re.search(pat6, string6)
    print("6-----", res6)
    pat7 = "python|php"  # 表示除了換行符都可以進行匹配
    string7 = "hgphpahg526pythongapgpre"
    res7 = re.search(pat7, string7)
    print("7-----", res7)
    # 模式修正符號 I 表示不區分大小寫 M進行多行匹配  L本地化識別匹配 U根據uniode解析我們的字元 S讓點號也能夠匹配模式換行符
    pat8 = "python"
    pst8 = "python"
    string8 = "jha;gh;dsghadgahghrhegaosidgPython"
    print("8-----", re.search(pat8, string8, re.I))
    # 貪婪模式的匹配
    # 懶惰模式的匹配
    pat10 = "p.*y"  # 貪婪模式
    pat11 = "p.?y"  # 懶惰模式
    string11 = "pfafasydfasdfydaspthonpysdapfsy"
    print("11----1", (re.match(pat10, string11)))  # 範圍更廣
    print("11----2", (re.search(pat11, string11)))  # 範圍準確
    # re.match()從頭開始搜尋 開始沒有匹配的直接退出了
    # re.search()
    # 全域性匹配函式
    print("12--------", re.compile(pat11).findall(string11))


if __name__ == '__main__':
    function3()

執行的截圖: