• python爬虫—— 抓取今日头条的街拍的妹子图


    AJAX 是一种用于创建快速动态网页的技术。 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。 

    近期在学习获取js动态加载网页的爬虫,决定通过实例加深理解。

    1、首先是url的研究(谷歌浏览器的审查功能)

    http://www.toutiao.com/search_content/?offset=0&format=json&keyword=%E8%A1%97%E6%8B%8D&autoload=true&count=20&cur_tab=1

    对应用get方法到url上获取信息。网页对应offset=0 、keyword=%E8%A1%97%E6%8B%8D  是会变的。如果要批量爬取,就得设置循环。

    当网页下拉,offset会20、40、60的变化,其实就是每次加载20个内容。

    2、

    通过requests获得response,进行json解析。

    还是一样的网页,切换到Preview,可以看到json的数据内容。title在['date'][0]['title']下,其他类似。

    import json
    import requests,os
    def download_pic(file,name,html):
        r = requests.get(html)
        filename=os.path.join(file,name+'.jpg')
        with open(filename,'wb') as f:
            f.write(r.content)
            
    url = 'http://www.toutiao.com/search_content/?offset=0&format=json&keyword=%E8%A1%97%E6%8B%8D&autoload=true&count=20&cur_tab=1'
    
    res = requests.get(url)
    json_data = json.loads(res.text)
    data = json_data['data']
    for i in data:
        print i['title']
        file_path = os.getcwd()+'image'
        print file_path
        for p in i['image_detail']:
            print p['url']
            name = p['url'].split('/')[-1]
            download_pic(file_path,name,p['url'])
    
       

    在当前目录新建image文件夹,然后爬虫下载图片。

    图片名截取url链接的后面部分31e30003d4be75c719ae.jpg

    例如http://p3.pstatp.com/large/31e30003d4be75c719ae

    结果如下:(仅供学习交流)

    循环什么的没写只爬取前20个链接的图片。

    --------------------------------------------------------------------------------------------------------------

    http://jandan.net/ooxx——煎蛋网

    同样是妹子图,有些网页不涉及json动态加载的就比较简单了,用beautifulsoup即可

    贴上代码匿了

    import requests,os,time
    from bs4 import BeautifulSoup
    def download_pic(file,name,html):
        r = requests.get(html)
        filename=os.path.join(file,name+'.jpg')
        with open(filename,'wb') as f:
            f.write(r.content)
            
    
    def get_url(url):
        res = requests.get(url)
        soup = BeautifulSoup(res.text,'lxml')
        data = soup.select(' div.text > p > img')
        print data
        for i in data:
            s = i.attrs['src'][2:]
            print s
            file_path = os.getcwd()+'imgage1'
            print file_path
            name = i.attrs['src'].split('/')[-1]
            download_pic(file_path,name,'http://'+s)
    
     
    for i in reversed(range(236)):
        url = 'http://jandan.net/ooxx/page-'+str(i)+'#comments'  
        if requests.get(url).status_code == 200:
            get_url(url)
        time.sleep(5)
  • 相关阅读:
    Maven------使用maven新建web项目出现问题 项目名称出现红色交叉
    Strut2------获取界面返回的session,application,parameter
    js之可迭代对象
    js字符串
    js之strict模式
    js系列之js简介
    python私有成员
    python之偏函数
    python之装饰器
    python之匿名函数
  • 原文地址:https://www.cnblogs.com/vhills/p/7295753.html
Copyright © 2020-2023  润新知