〇. python 基础html
先放上python 3 的官方文档:https://docs.python.org/3/ (看文档是个好习惯)python
关于python 3 基础语法方面的东西,网上有不少,你们能够自行查找.正则表达式
一. 最简单的爬取程序浏览器
爬取百度首页源代码:cookie
来看上面的代码:python爬虫
The urllib.requestmodule defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.less
urllib.request.urlopen(url, data=None, [timeout, ]***, cafile=None, capath=None, cadefault=False, context=None)For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponseobject slightly modified.< 出自: https://docs.python.org/3/library/urllib.request.html >函数
二 模拟浏览器爬取信息学习
在访问某些网站的时候,网站一般会用判断访问是否带有头文件来鉴别该访问是否为爬虫,用来做为反爬取的一种策略。网站
先来看一下Chrome的头信息(F12打开开发者模式)以下:
如图,访问头信息中显示了浏览器以及系统的信息(headers所含信息众多,具体可自行查询)
Python中urllib中的request模块提供了模拟浏览器访问的功能,代码以下:
from urllib import request url = 'http://www.baidu.com' # page = request.Request(url) # page.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36') headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} page = request.Request(url, headers=headers) page_info = request.urlopen(page).read().decode('utf-8') print(page_info)
能够经过add_header(key, value) 或者直接以参数的形式和URL一块儿请求访问,urllib.request.Request()
urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
在学习中有迷茫不知如何学习的朋友小编推荐一个学Python的学习q u n 227 -435- 450能够来了解一块儿进步一块儿学习!免费分享视频资料
三 爬虫利器Beautiful Soup
Beautiful Soup是一个能够从HTML或XML文件中提取数据的Python库.它可以经过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.
文档中的例子其实说的已经比较清楚了,那下面就以爬取简书首页文章的标题一段代码来演示一下:
先来看简书首页的源代码:
能够发现简书首页文章的标题都是在<a/>标签中,而且class='title',因此,经过
find_all('a', 'title')
即可得到全部的文章标题,具体实现代码及结果以下:
# -*- coding:utf-8 -*- from urllib import request from bs4 import BeautifulSoup url = r'http://www.jianshu.com' # 模拟真实浏览器进行访问 headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} page = request.Request(url, headers=headers) page_info = request.urlopen(page).read() page_info = page_info.decode('utf-8') # 将获取到的内容转换成BeautifulSoup格式,并将html.parser做为解析器 soup = BeautifulSoup(page_info, 'html.parser') # 以格式化的形式打印html # print(soup.prettify()) titles = soup.find_all('a', 'title') # 查找全部a标签中class='title'的语句 # 打印查找到的每个a标签的string for title in titles: print(title.string)
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,下表列出了主要的解析器,以及它们的优缺点:
四 将爬取的信息存储到本地
以前咱们都是将爬取的数据直接打印到了控制台上,这样显然不利于咱们对数据的分析利用,也不利于保存,因此如今就来看一下如何将爬取的数据存储到本地硬盘。
1 对.txt文件的操做
读写文件是最多见的操做之一,python3 内置了读写文件的函数:open
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None))Open file and return a corresponding file object. If the file cannot be opened, an OSErroris raised.
其中比较经常使用的参数为file和mode,参数file为文件的路径,参数mode为操做文件的方式(读/写),函数的返回值为一个file对象,若是文件操做出现异常的话,则会抛出 一个OSError
还以简书首页文章题目为例,将爬取到的文章标题存放到一个.txt文件中,具体代码以下:
# -*- coding:utf-8 -*- from urllib import request from bs4 import BeautifulSoup url = r'http://www.jianshu.com' headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} page = request.Request(url, headers=headers) page_info = request.urlopen(page).read().decode('utf-8') soup = BeautifulSoup(page_info, 'html.parser') titles = soup.find_all('a', 'title') try: # 在E盘以只写的方式打开/建立一个名为 titles 的txt文件 file = open(r'E: itles.txt', 'w') for title in titles: # 将爬去到的文章题目写入txt中 file.write(title.string + ' ') finally: if file: # 关闭文件(很重要) file.close()
open中mode参数的含义见下表:
其中't'为默认模式,'r'至关于'rt',符号能够叠加使用,像'r+b'
另外,对文件操做必定要注意的一点是:打开的文件必定要关闭,不然会占用至关大的系统资源,因此对文件的操做最好使用try:...finally:...的形式。可是try:...finally:...的形式会使代码显得比较杂乱,所幸python中的with语句能够帮咱们自动调用close()而不须要咱们写出来,因此,上面代码中的try:...finally:...可以使用下面的with语句来代替:
with open(r'E: itle.txt', 'w') as file: for title in titles: file.write(title.string + ' ')
效果是同样的,建议使用with语句
2 图片的储存
有时候咱们的爬虫不必定只是爬取文本数据,也会爬取一些图片,下面就来看怎么将爬取的图片存到本地磁盘。
咱们先来选好目标,知乎话题:女生怎么健身锻造好身材? (单纯由于图多,不要多想哦 (# _ # ) )
看下页面的源代码,找到话题下图片连接的格式,如图:
能够看到,图片在img标签中,且class=origin_image zh-lightbox-thumb,并且连接是由.jpg结尾,咱们即可以用Beautiful Soup结合正则表达式的方式来提取全部连接,以下:
links = soup.find_all('img', "origin_image zh-lightbox-thumb",src=re.compile(r'.jpg$'))
提取出全部连接后,使用request.urlretrieve来将全部连接保存到本地
Copy a network object denoted by a URL to a local file. If the URL points to a local file, the object will not be copied unless filename is supplied. Return a tuple (filename, headers)where filename is the local file name under which the object can be found, and headers is whatever the info()method of the object returned by urlopen()returned (for a remote object). Exceptions are the same as for urlopen().
具体实现代码以下:
# -*- coding:utf-8 -*- import time from urllib import request from bs4 import BeautifulSoup import re url = r'https://www.zhihu.com/question/22918070' headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} page = request.Request(url, headers=headers) page_info = request.urlopen(page).read().decode('utf-8') soup = BeautifulSoup(page_info, 'html.parser') # Beautiful Soup和正则表达式结合,提取出全部图片的连接(img标签中,class=**,以.jpg结尾的连接) links = soup.find_all('img', "origin_image zh-lightbox-thumb",src=re.compile(r'.jpg$')) # 设置保存的路径,不然会保存到程序当前路径 local_path = r'E:Pic' for link in links: print(link.attrs['src']) # 保存连接并命名,time防止命名冲突 request.urlretrieve(link.attrs['src'], local_path+r'%s.jpg' % time.time())
运行结果