zoukankan      html  css  js  c++  java
  • 用Python爬虫爬取“女神吧”上的照片。

    爬取的网页链接为https://tieba.baidu.com/p/5177270774

    是一个美女警花哦!

    所用Python环境为:python 3.3.2   用到的库为:urllib.request    re

    下面上代码:

    import urllib.request
    import re
    
    #获得url的html 源码格式,其中使用了一个通过修改User-Agent实现了隐藏
    def open_url(url):
        req = urllib.request.Request(url)
        req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36')
        page = urllib.request.urlopen(req)
        html = page.read().decode('utf-8') #二进制的utf-8要解码得到html代码(Unicode)
        return html
    
    
    #写正则表达式,获得html代码
    def get_image(html):
        p = r'<img class="BDE_Image" src="([^"]+.jpg)"' #正则表达式 [^]中的^是取反的意思
        temp = re.findall(p,html)
        i = 0
        page = 'C:/Users/lenovo/Desktop/mm/'
        for each in temp:
            i += 1
            file = open(page+str(i)+'.jpg','wb')
            each = urllib.request.urlopen(each).read()   #将图片链接读出来写入文件中
            file.write(each)
            file.close()
            
        
    def main(url):
        get_image(open_url(url))
    
    #规定只有直接运行这个模块才能执行主程序
    if __name__ == '__main__':
        url = 'https://tieba.baidu.com/p/5177270774' 
        main(url)

    下面是爬取结果:

    当然,这个爬虫是不完善的,除了四张美女图片外还多了一些慕名奇妙的图片,但是总的来说还是爬到了美女的图片的。

  • 相关阅读:
    IE6碰到的兼容问题小结
    Ueditor的asp版本,上传测试无问题
    localStorage存取json数据
    asp版 QQ登录 oauth2.0
    phoneGap API调用摄像头并上传图片
    ASP.NET Ajax 控件之应用一(CollapsiblePanelExtender控件的使用)
    web网页配色
    DispatcherTimer与Dispatcher小小应用
    小说ICommand
    例说INotifyPropertyChanged接口
  • 原文地址:https://www.cnblogs.com/jeavenwong/p/7078230.html
Copyright © 2011-2022 走看看