Python爬虫学习 - day1 - 爬取图片

利用Python完成简单的图片爬取

  最近学习到了爬虫,瞬时觉得很高大上,想取什么就取什么,感觉要上天。这里分享一个简单的爬取汽车之家文章列表的图片教程,供大家学习。

需要的知识点储备

  本次爬虫脚本依赖两个模块:requests模块,BeautifulSoup模块。其中requests模块完成url的请求,而BeautifulSoup模块负责解析Html标签。

requests模块

  requests.get(url)  向URL发起GET请求

  requests.post(url)  向URL发起POST请求

>>> import requests
>>> response = requests.get('https://www.baidu.com')
>>> print(response.text)
<!DOCTYPE html>

<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=styleshee
......
......
</body> </html>

# 上面为页面信息

>>> 

可以看到response是服务端返回的信息:在requests内部也被封装成了一个对象,它具有很多属性,主要如下:

  1. response.text:以字符串的形式显示返回的信息  
  2. response.content:以字节的形式显示返回的信息(bytes对象)  
  3. response.encode:告诉requests 已什么编码格式进行解析
  4. response.url:请求的url(当使用get方式发送数据时,可以显示具体的url)
  5. response.encoding:查看requests自动识别的网页编码
  6. response.json():对于返回值是json格式的,那么可以直接使用json(),提取成字典
  7. response.headers:获取响应头信息(响应头是一个字典,支持字典操作)
  8. response.cookies:获取服务端响应的cookies

数据提交

  访问站点时进行数据提交根据请求的方式不同,主要分两种,即GET提交,POST提交。

  当使用GET方式提交时,数据是拼接到URL进行提交的,那么这个时候需要使用params参数来定制提交的数据(提交的数据为字典类型)

import requests

data = {'wd': '词典'}
response = requests.get('http://www.baidu.com/s', params=data)
print(response.url)    # http://www.baidu.com/s?wd=%E8%AF%8D%E5%85%B8     --> 中文会被编码
print(response.text)   # 返回的内容

  当使用POST方式提交时,数据是放在请求体中提交的,那么这个时候就需要使用data参数了(提交的数据为字典类型)

import requests

data = {'wd': '词典'}
response = requests.post('http://www.baidu.com/s', data=data)   # 注意

PS:requests的data参数使用application/x-www-form-urlencoded对POST数据编码。如果要传递JSON数据,可以使用json参数来让requests对数据使用json编码。

文件上传

上传文件需要更复杂的编码格式,但是requests把它简化成files参数:

>>> upload_files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=upload_files)

在读取文件时,注意务必使用'rb'即二进制模式读取,这样获取的bytes长度才是文件的长度。

post()方法替换为put()delete()等,就可以以PUT或DELETE方式请求资源。

BeautifulSoup模块

  soup = BeautifulSoup(html页面,features='html.parser')    把返回的页面交给BeautifulSoup进行处理,生成soup对象,其中features表示使用的解析方式,这里使用html.parser,因为内置,其他的也可以使用lxml,速度要快于html.parser但是需要额外安装。

  soup 是BeautifulSoup对象,它具有查找修改获取等等众多功能。

    1. soup.find()  用于对HTML标签进行查找,找到一个就返回
    2. soup.find_all()  用户对HTML标签进行遍历,查到所有的标签后,以列表的形式返回  
    3. soup.get()   获取标签的单个属性的值
    4. soup.attrs        获取标签的所有属性,返回字典  
    5. soup.text    获取标签的内容

利用Python完成汽车直接文章列表的图片爬取

  想要爬取什么信息,那么首先需要我们查看一下相关网页的源码信息,确定要爬取的标签以及属性。

确认爬取信息

  打开http://www.autohome.com.cn/all/ 文章评测页面。打开调试模式,查看网页源码

<div id="auto-channel-lazyload-article" class="article-wrapper">

    <ul class="article">

        <li data-artidanchor="908300">
            <a href="//www.autohome.com.cn/news/201710/908300.html#pvareaid=102624">
                <div class="article-pic"><img
                        src="//www2.autoimg.cn/newsdfs/g21/M06/8A/59/120x90_0_autohomecar__wKgFVVnpmymAYrwNAAFqGWS9P0k275.jpg">
                </div>
                <h3>全新外观设计 全新Vanquish谍照曝光</h3>
                <div class="article-bar">
                    <span class="fn-left">56分钟前</span>
                    <span class="fn-right">
                                        <em><i class="icon12 icon12-eye"></i>4130</em>
                                        <em data-class="icon12 icon12-infor" data-articleid="908300"><i
                                                class="icon12 icon12-infor"></i>19</em>
                                    </span>
                </div>
                <p>[汽车之家 海外谍照] 日前,有海外媒体曝光了一组阿斯顿·马丁全新一代Vanquish车型路试谍照,新车在外观部分进行了全面的革新,此外,...</p>
            </a>
        </li>

        <li data-artidanchor="908294">
            <a href="//www.autohome.com.cn/culture/201710/908294.html#pvareaid=102624">
                <div class="article-pic"><img
                        src="//www3.autoimg.cn/newsdfs/g15/M10/B6/51/120x90_0_autohomecar__wKjByFnpd-uAVVwWAAFlp02ujCY900.jpg">
                </div>
                <h3>买游戏送汽车 《GT赛车》发布最强同捆</h3>
                <div class="article-bar">
                    <span class="fn-left">3小时前</span>
                    <span class="fn-right">
                                        <em><i class="icon12 icon12-eye"></i>8318</em>
                                        <em data-class="icon12 icon12-infor" data-articleid="908294"><i
                                                class="icon12 icon12-infor"></i>49</em>
                                    </span>
                </div>
                <p>[汽车之家 车坛勐料] 先来做个名字解释,“同捆”是指游戏主机外加一款或多款游戏的套装,很多时候“同捆包”中还会包含一些该游戏的周边产品,比如模型。...</p>
            </a>
        </li>

        ...
        ...
        ...

    </ul>


</div>

  观察源码发现,得出的结论:

    1. 要获取的信息都被一个div标签包裹,并且该标签具有id属性,由于id属性页面唯一,可以通过该属性确定查找范围
    2. li标签是一条一条的文章信息
    3. 每个文章信息中的img标签的src属性即为图片的地址

完整的代码

import requests
from bs4 import BeautifulSoup



response = requests.get(url='http://www.autohome.com.cn/all/')
response.encoding = 'gbk'
soup = BeautifulSoup(response.text,features='html.parser')
tag = soup.find(id='auto-channel-lazyload-article')
title = tag.find_all('li')
for tag in title:
    if tag.find('h3'):
        print(tag.find('h3').text)
    if tag.find('a'):
        print('http:'+tag.find('a').get('href'))
    if tag.find('img'):
        img_url = tag.find('img').get('src')
        imgname = img_url.split('/')[-1]
        img_obj = requests.get('http:'+img_url)
        with open('imgs/%s' % imgname,mode='wb') as f:
            f.write(img_obj.content)

注意:

  • 由于汽车之家页面使用gbk编码,所以这里指定编码格式为gbk,否则会出现乱码。
  • 获取图片的url然后下载,把图片保存在本地
posted @ 2017-10-20 15:04  SpeicalLife  阅读(535)  评论(1编辑  收藏  举报