美文网首页
Python写爬虫

Python写爬虫

作者: 齐滇大圣 | 来源:发表于2016-04-07 16:40 被阅读379次

环境准备

我个人使用的是mac,mac预装的python环境是python2.x。
查看python版本:在终端(Terminal)中输入“python”。

安装pip:

下载地址:https://pypi.python.org/pypi/pip
解压,安装:
<code>sudo python setup.py install</code>

安装BeautifulSoup:

<code>pip install BeautifulSoup</code>
Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。

编码运行

抓取该网站图片:http://www.win4000.com/meinvtag34.html
创建search.py文件并编写对应代码
代码:
#!/usr/bin/python
#-- coding: utf-8 --
#encoding=utf-8

import urllib2
import urllib
import os
from BeautifulSoup import BeautifulSoup

def getAllImageLink():
    html = urllib2.urlopen('http://www.win4000.com/meinvtag34.html').read()
    soup = BeautifulSoup(html)

    liResult = soup.findAll('li',attrs={"class":"box"})
    numberIndex = 0
    for li in liResult:
        imageEntityArray = li.findAll('img')
        for image in imageEntityArray:
            link = image.get('src')
            imageName = 'image' + str(numberIndex)
            numberIndex = numberIndex + 1
            filesavepath = '/Users/YMY/Desktop/imageUrl/%s.jpg' % imageName
            urllib.urlretrieve(link,filesavepath)
            print filesavepath

if __name__ == '__main__':
    getAllImageLink()

终端运行:

python search.py

最后就会在对应的文件夹中生成爬下来的图片。

需要学习

有些网页的抓取可能没那么简单,不同的网站规则都是不一样的。这时候就需要我们学会怎么去遍历,怎么找到我们需要的元素。Beautiful Soup里还有很多对应的方法需要学习,这里放上一份Beautiful Soup 4.2.0 文档为以后学习使用。

参考

iOS程序员如何使用python写网路爬虫

相关文章

网友评论

      本文标题:Python写爬虫

      本文链接:https://www.haomeiwen.com/subject/ahimlttx.html