python3 爬虫-入门
来源:互联网 发布:5sing mac版 编辑:程序博客网 时间:2024/06/05 05:50
1.最简单的爬虫
爬百度的首页,并打印数据:
# -*- coding: utf-8 -*-# 导入库from urllib import request# 请求response = request.urlopen("http://www.baidu.com/")# 解码content = response.read().decode('utf-8')# 输出print(content)
2.增加搜索参数
在百度中搜索“中国”:
import urllib.requestdata = {}# word=中国data['word'] = '中国'url_values = urllib.parse.urlencode(data)url = "http://www.baidu.com/s?"# 组合搜索的get请求full_url = url + url_values# 请求data = urllib.request.urlopen(full_url).read()# 解码data = data.decode('UTF-8')# 打印print(data)
3.爬出图片地址
爬出豆瓣的页面,然后,正则匹配出图片地址。
# -*- coding: UTF-8 -*-import urllib.requestimport reimport sslssl._create_default_https_context = ssl._create_unverified_context# 获取html数据def getHtml(url): page = urllib.request.urlopen(url) html_data = page.read() return html_data# 获取图片列表def getImg(html_data): # src=" 开头 .jpg > 结尾 reg = r'src="(.+?\.jpg|.png)">' image_reg = re.compile(reg) image_list = re.findall(image_reg, html_data) return image_listhtml = getHtml('https://site.douban.com/120100/')html_str = html.decode('utf-8')# 输出图片列表print(getImg(html_str))
说明:
1.现在的网页基本都是https所以要加ssl模块:
import sslssl._create_default_https_context = ssl._create_unverified_context
4.下载图片
# coding=utf-8import urllibimport urllib.requestimport reimport sslssl._create_default_https_context = ssl._create_unverified_contextdef getHtml(url): page = urllib.request.urlopen(url) html_data = page.read() return html_datadef getImg(html_data): # src=" 开头 .jpg "> 结尾 reg = r'src="(.+?\.jpg|.png)">' img_reg = re.compile(reg) img_list = re.findall(img_reg, html_data) return img_listdef cbk(a, b, c): """ 回调函数 @a:已经下载的数据块 @b:数据块的大小 @c:远程文件的大小 """ per = 100.0 * a * b / c if per > 100: per = 100 print('%.2f%%' % per)def downloadImg(img_list): x = 0 for img_url in img_list: try: print('===== download =====') print('download image %s' % x) # python3 不能用原来的 urllib.urlretrieve 而要用 urllib.request.urlretrieve urllib.request.urlretrieve(img_url, 'data/%s.jpg' % x, cbk) except urllib.request.HTTPError as e: print('HTTPError:', e.code) print('HTTPError:', e.reason) continue except urllib.request.URLError as e: print('URLError:', e.reason) continue x += 1html = getHtml('https://site.douban.com/120100/')html_str = html.decode('utf-8')# 正则匹配 查找图片image_list = getImg(html_str)print(image_list)# 下载图片downloadImg(image_list)
说明:
1.使用urllib.request.urlretrieve 根据地址下载图片.
2.输出下载进度的cbk函数。
def cbk(a, b, c): """ 回调函数 @a:已经下载的数据块 @b:数据块的大小 @c:远程文件的大小 """ per = 100.0 * a * b / c if per > 100: per = 100 print('%.2f%%' % per)# python3 不能用原来的 urllib.urlretrieve 而要用 urllib.request.urlretrieveurllib.request.urlretrieve(img_url, 'data/%s.jpg' % x, cbk)
5.升级正则匹配
使用Beautifulsoup4, 升级正则匹配。
# coding=utf-8# beautifulsoup4 的使用import urllibimport urllib.requestimport refrom bs4 import BeautifulSoupimport sslssl._create_default_https_context = ssl._create_unverified_contextdef getHtml(url): page = urllib.request.urlopen(url) html_data = page.read() return html_datadef getImg(html_data): # src=" 开头 .jpg "> 结尾 reg = r'src="(.+?\.jpg|.png)">' img_reg = re.compile(reg) img_list = re.findall(img_reg, html_data) return img_listdef cbk(a, b, c): """ 回调函数 @a:已经下载的数据块 @b:数据块的大小 @c:远程文件的大小 """ per = 100.0 * a * b / c if per > 100: per = 100 print('%.2f%%' % per)def downloadImg(img_list): x = 0 for img_url in img_list: try: print('===== download =====') print('download image %s' % x) # python3 不能用原来的 urllib.urlretrieve 而要用 urllib.request.urlretrieve urllib.request.urlretrieve(img_url, 'data/%s.jpg' % x, cbk) except urllib.request.HTTPError as e: print('HTTPError:', e.code) print('HTTPError:', e.reason) continue except urllib.request.URLError as e: print('URLError:', e.reason) continue x += 1def printImgUrlFromHtml(html_str): soup = BeautifulSoup(html_str, 'html.parser') img_tag_list = soup.find_all('img') x = 0 for img_tag in img_tag_list: img_url = img_tag.get('src') print('image[%s]:' % x, img_url) x += 1html = getHtml('https://site.douban.com/120100/')html_str = html.decode('utf-8')# 正则匹配 查找图片image_list = getImg(html_str)# 打印图片地址printImgUrlFromHtml(html_str)
说明:
1.使用BeautifulSoup4,将html页面解析成html Dom节点,然后查找想要的元素。
soup = BeautifulSoup(html_str, 'html.parser')img_tag_list = soup.find_all('img')
6.将爬到的数据保存到文件
将爬到的数据,解析完成后,存入txt文件中。
# coding=utf-8# 保存到txt文件中import urllibimport urllib.requestimport refrom bs4 import BeautifulSoupimport sslssl._create_default_https_context = ssl._create_unverified_contextdef getHtml(url): page = urllib.request.urlopen(url) html_data = page.read() return html_datadef getImg(html_data): # src=" 开头 .jpg "> 结尾 reg = r'src="(.+?\.jpg)">' img_reg = re.compile(reg) img_list = re.findall(img_reg, html_data) return img_listdef cbk(a, b, c): """ 回调函数 @a:已经下载的数据块 @b:数据块的大小 @c:远程文件的大小 """ per = 100.0 * a * b / c if per > 100: per = 100 print('%.2f%%' % per)def downloadImg(img_list): x = 0 for img_url in img_list: try: print('===== download =====') print('download image %s' % x) # python3 不能用原来的 urllib.urlretrieve 而要用 urllib.request.urlretrieve urllib.request.urlretrieve(img_url, 'data/%s.jpg' % x, cbk) except urllib.request.HTTPError as e: print('HTTPError:', e.code) print('HTTPError:', e.reason) continue except urllib.request.URLError as e: print('URLError:', e.reason) continue x += 1def printImgUrlFromHtml(html_str): soup = BeautifulSoup(html_str, 'html.parser') img_tag_list = soup.find_all('img') img_list = [] x = 0 for img_tag in img_tag_list: img_url = img_tag.get('src') print('image[%s]:' % x, img_url) # saveFile(img_url) img_list.append('image[%s]: %s \n' % (x, img_url)) x += 1 saveLinesFile(img_list)def saveLinesFile(lines_data): save_path = 'data/images2.txt' # wb 写入二进制 # w 写入文本 # 1.打开文件 file_point = open(save_path, 'w') # 2.写入数据 file_point.writelines(lines_data) # 3.关闭文件 file_point.close()html = getHtml('https://site.douban.com/120100/')html_str = html.decode('utf-8')# 正则匹配 查找图片image_list = getImg(html_str)# 打印图片地址printImgUrlFromHtml(html_str)
说明:
1.文件的操作封装在saveLinesFile函数中:
def saveLinesFile(lines_data)
7.文件使用日期命名
# coding=utf-8# 保存到txt文件中import urllibimport urllib.requestimport refrom bs4 import BeautifulSoupimport datetimeimport timeimport sslssl._create_default_https_context = ssl._create_unverified_contextdef getHtml(url): page = urllib.request.urlopen(url) html_data = page.read() return html_datadef getImg(html_data): # src=" 开头 .jpg "> 结尾 reg = r'src="(.+?\.jpg)">' img_reg = re.compile(reg) img_list = re.findall(img_reg, html_data) return img_listdef cbk(a, b, c): """ 回调函数 @a:已经下载的数据块 @b:数据块的大小 @c:远程文件的大小 """ per = 100.0 * a * b / c if per > 100: per = 100 print('%.2f%%' % per)def downloadImg(img_list): x = 0 for img_url in img_list: try: print('===== download =====') print('download image %s' % x) # python3 不能用原来的 urllib.urlretrieve 而要用 urllib.request.urlretrieve urllib.request.urlretrieve(img_url, 'data/%s.jpg' % x, cbk) except urllib.request.HTTPError as e: print('HTTPError:', e.code) print('HTTPError:', e.reason) continue except urllib.request.URLError as e: print('URLError:', e.reason) continue x += 1def printImgUrlFromHtml(html_str): soup = BeautifulSoup(html_str, 'html.parser') img_tag_list = soup.find_all('img') img_list = [] x = 0 for img_tag in img_tag_list: img_url = img_tag.get('src') print('image[%s]:' % x, img_url) # saveFile(img_url) img_list.append('image[%s]: %s \n' % (x, img_url)) x += 1 saveLinesFile(img_list)def saveFile(data): save_path = 'data/images1.txt' # wb 写入二进制 # w 写入文本 # 1.打开文件 file_point = open(save_path, 'w+') # 2.写入数据 file_point.write(data) # 3.关闭文件 file_point.close()def saveLinesFile(lines_data): time_str = time.strftime("%Y-%m-%d", time.localtime()) print(time_str) save_path = 'data/%s.txt' % time_str # wb 写入二进制 # w 写入文本 # 1.打开文件 file_point = open(save_path, 'w') # 2.写入数据 file_point.writelines(lines_data) # 3.关闭文件 file_point.close()html = getHtml('https://site.douban.com/120100/')html_str = html.decode('utf-8')# 正则匹配 查找图片image_list = getImg(html_str)# 打印图片地址printImgUrlFromHtml(html_str)
说明:
1.获取当前日期的字符串:
time_str = time.strftime("%Y-%m-%d", time.localtime())
阅读全文
0 0
- python3 爬虫-入门
- python3 爬虫技术入门
- python3 爬虫入门
- python3爬虫入门
- Python3爬虫入门学习
- Python3 爬虫快速入门攻略
- python3爬虫之入门和正则表达式
- Python3爬虫之入门和正则表达式
- Python3爬虫之入门和正则表达式
- Python3.6 学习爬虫入门篇
- python3爬虫之入门和正则表达式
- Python3网络爬虫快速入门实战解析
- [Python3]爬虫入门之正则表达式
- Python3 网络爬虫入门知识碎片
- python3爬虫初级入门和正则表达式
- Python3爬虫学习1:入门篇
- python3 [入门基础实战] 爬虫入门之xpath的学习
- python3 爬虫
- Java IO最详解
- 关于前端布局的思考
- C++重载原理
- 非root用户CentOS下安装JDK1.7
- 鸣人的影分身
- python3 爬虫-入门
- 烂代码传奇
- 由浅入深理解java集合(三)
- Android:最全面的 Webview 详解
- Android ormlite DB错误 Unable to run insert stmt on object
- swift学习网站
- Java:反射机制详解
- Java异常处理总结
- 1143: 最大值—多种进制