用python写网络爬虫-下载网页

开始学写爬虫啦,但是刚看书开头说本书以python2.7为案例讲解,很多模块未适配到python3.x,不过我看这本书的时候发现他说的很多没适配的模块基本都适配过来了,所以就决定用python3.6来写,正好体会下3和2的差别

1.首先python3中的urllib2模块和urllib模块合并,2中使用urllib2.xxx替换为使用urllib.request.xxx即可

import urllib.request  
import urllib.error
import re

def download(url):
    return urllib.request.urlopen(url).read()

def save(file_name, file_content):
    with open(file_name.replace('/', '_') + ".html", "wb") as f:
        f.write(file_content)

murl="http://blog.csdn.net/joliph"
html = download(murl)
save(re.split('/',murl)[-1], html)

这里使用了另外一个模块叫re模块,
re.split分割含有多种分割符的字符串,返回分割后的字符串列表,直接使用-1找到网页的最后一部分名字,非常实用

save(murl.split('/')[-1], html)

这里只有一种分隔符“/”,所以这样写也可以

更新!!

import urllib.request  
import urllib.error
import re

def download(url):
    print("downloading:"+url)
    headers={'User-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
    request=urllib.request.Request(url,headers=headers)
    try:
        content=urllib.request.urlopen(request).read()
    except urllib.error.URLError as e:
        print("download error:"+e.reason)
        content=None
    return content

def save(file_name, file_content):
    print("saving.......")
    try:
        with open(file_name + ".html", "wb") as f:
            f.write(file_content)
    except TypeError:
        print("TypeError")


murl="http://www.budejie.com/"
html = download(murl)
save(re.split('/',murl)[-1], html)
为两个函数分别增加了一种错误类型判断以及运行过程提示
增加了用户代理,防止部分网页阻止访问的情况发生
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值