美文网首页python互联网科技iOS Developer
用Python写爬虫,来来来,你也能学会

用Python写爬虫,来来来,你也能学会

作者: adc9c8f3920d | 来源:发表于2017-06-20 13:54 被阅读258次

Python

Python爬虫,一般用于抓取特定的内容,最近想学学,通过网络抓取自己想要的内容。案例程序主要功能:抓取我们学校校园网新闻中的图片。

#coding=utf-8

import urllib

import re

# 定义个函数 抓取网页内容

def getHtml(url):

webPage = urllib.urlopen(url)

html = webPage.read()

return html

# 定义一个函数 抓取网页中的图片

def getNewsImgs(html):

# 正则表达式

reg = r'src="(.+?\.jpg)"'

img = re.compile(reg)

# 获取网页中所有符合条件的图片url

imglist = re.findall(img,html)

x = 0

# 根据图片地址下载图片并重命名

for imgUrl in imglist:

urllib.urlretrieve("http://www.abc.edu.cn/news/"+imgUrl,'news-%s.jpg' % x)

x += 1

# 获取网页

html = getHtml("http://www.abc.edu.cn/news/show.aspx?id=21413&cid=5")

# 抓取图片

print getNewsImgs(html)

这样就可以抓取到校园新闻中的图片了。上面是用正则表达式来匹配数据项,但是写起来容易出错,如果有过DOM开发经验或者使用过jQuery的朋友看到BeautifulSoup就像是见到了老朋友一样。首先安装BeautifulSoup,Mac安装BeautifulSoup很简单,打开终端,执行以下语句,然后输入密码即可安装。

sudo easy_install beautifulsoup4

改代码

#coding=utf-8

import urllib

from bs4 import BeautifulSoup

# 定义个函数 抓取网页内容

def getHtml(url):

webPage = urllib.urlopen(url)

html = webPage.read()

return html

# 定义一个函数 抓取网页中的图片

def getNewsImgs(html):

# 创建BeautifulSoup

soup = BeautifulSoup(html, "html.parser")

# 查找所有的img标签

urlList = soup.find_all("img")

length = len(urlList)

# 遍历标签 下载图片

for i in range(length):

imgUrl = urlList[i].attrs["src"]

urllib.urlretrieve("http://www.abc.edu.cn/news/"+imgUrl,'news-%s.jpg' % i)

# 获取网页

html = getHtml("http://www.abc.edu.cn/news/show.aspx?id=21430&cid=5")

# 抓取图片

getNewsImgs(html)

执行效果如下:

Python写爬虫就是如此简单,还不快试试?我有建立一个python学习交流群,在群里我们相互帮助,相互关心,相互分享内容,这样出问题帮助你的人就比较多,群号是301,还有056,最后是051,这样就可以找到大神聚合的群,如果你只愿意别人帮助你,不愿意分享或者帮助别人,那就请不要加了,你把你会的告诉别人这是一种分享

相关文章

网友评论

本文标题:用Python写爬虫,来来来,你也能学会

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