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

xiaoxiao2021-02-28  104

开始学写爬虫啦,但是刚看书开头说本书以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) 为两个函数分别增加了一种错误类型判断以及运行过程提示 增加了用户代理,防止部分网页阻止访问的情况发生
转载请注明原文地址: https://www.6miu.com/read-37934.html

最新回复(0)