艺术人生经验 | Python爬虫基础


本文梳理了网页解析、抓包、爬虫基本流程等基础知识。全文约 6250 字,读完可能需要 9 分钟。 

作者:voidking 

原文:https://segmentfault.com/a/1190000008191015

前言

Python 非常适合用来开发网页爬虫,理由如下:

1、抓取网页本身的接口

相比与其他静态编程语言,如 java , c#, c ++, python 抓取网页文档的接口更简洁;相比其他动态脚本语言,如 perl , shell , python 的 urllib 包提供了较为完整的访问网页文档的 API 。(当然 ruby 也是很好的选择)

此外,抓取网页有时候需要模拟浏览器的行为,很多网站对于生硬的爬虫抓取都是封杀的。这是我们需要模拟 user agent的行为构造合适的请求,譬如模拟用户登陆、模拟session/cookie的存储和设置。在python里都有非常优秀的第三方包帮你搞定,如Requests,mechanize。

2、网页抓取后的处理

抓取的网页通常需要处理,比如过滤 html 标签,提取文本等。 python 的 beautifulsoap 提供了简洁的文档处理功能,能用极短的代码完成大部分文档的处理。

其实以上功能很多语言和工具都能做,但是用 python 能够干得最快,最干净。

Life is short , you need python. 


PS :python 2. x 和 python 3. x 有很大不同,本文只讨论 python 3. x 的爬虫实现方法。

爬虫架构

架构组成

URL 管理器:管理待爬取的 url 集合和已爬取的 url 集合,传送待爬取的 url 给网页下载器。

网页下载器( urllib ):爬取 url 对应的网页,存储成字符串,传送给网页解析器。

网页解析器( BeautifulSoup ):解析出有价值的数据,存储下来,同时补充 url 到 URL 管理器。

运行流程

URL 管理器

基本功能

  • 添加新的 url 到待爬取 url 集合中。

  • 判断待添加的 url 是否在容器中(包括待爬取 url 集合和已爬取 url 集合)。

  • 获取待爬取的 url 。

  • 判断是否有待爬取的 url 。

  • 将爬取完成的 url 从待爬取 url 集合移动到已爬取 url 集合。

存储方式

1、内存( python 内存) 待爬取 url 集合:set() 已爬取 url 集合:set()

2、关系数据库( mysql ) urls( url , is_crawled)

3、缓存( redis ) 待爬取 url 集合: set() 已爬取 url 集合: set()

大型互联网公司,由于缓存数据库的高性能,一般把 url 存储在缓存数据库中。小型公司,一般把 url 存储在内存中,如果想要永久存储,则存储到关系数据库中。

网页下载器( urllib )

将 url 对应的网页下载到本地,存储成一个文件或字符串。

基本方法

新建 baidu.py ,内容如下:

  
  
  
  
  1. import urllib.request

  2. response = urllib.request.urlopen('http://www.baidu.com')

  3. buff = response.read()

  4. html = buff.decode("utf8")

  5. print(html)

命令行中执行 python baidu.py ,则可以打印出获取到的页面。

构造 Request

上面的代码,可以修改为:

  
  
  
  
  1. import urllib.request

  2. request = urllib.request.Request('http://www.baidu.com')

  3. response = urllib.request.urlopen(request)

  4. buff = response.read()

  5. html = buff.decode("utf8")

  6. print(html)

携带参数

新建 baidu 2. py ,内容如下:

  
  
  
  
  1. import urllib.request

  2. import urllib.parse

  3. url = 'http://www.baidu.com'

  4. values = {'name': 'voidking', 'language': 'Python'}

  5. data = urllib.parse.urlencode(values).encode(

  6.    encoding='utf-8', errors='ignore')

  7. headers = {

  8.    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}

  9. request = urllib.request.Request(

  10.    url=url, data=data, headers=headers, method='GET')

  11. response = urllib.request.urlopen(request)

  12. buff = response.read()

  13. html = buff.decode("utf8")

  14. print(html)

使用 Fiddler 监听数据

我们想要查看一下,我们的请求是否真的携带了参数,所以需要使用 fiddler 。 打开 fiddler 之后,却意外发现,上面的代码会报错504,无论是 baidu.py 还是 baidu 2. py 。

虽然 python 有报错,但是在 fiddler 中,我们可以看到请求信息,确实携带了参数。

经过查找资料,发现python以前版本的Request都不支持代理环境下访问https。但是,最近的版本应该支持了才对。那么,最简单的办法,就是换一个使用http协议的url来爬取,比如,换成 http://www.csdn.net。结果,依然报错,只不过变成了400错误。

然而,然而,然而。。。神转折出现了!!!

当我把url换成 http://www.csdn.net/后,请求成功!没错,就是在网址后面多加了一个斜杠 /。同理,把 http://www.baidu.com改成 http://www.baidu.com/,请求也成功了!神奇!!!

添加处理器

  
  
  
  
  1. import urllib.request

  2. import http.cookiejar

  3. # 创建cookie容器

  4. cj = http.cookiejar.CookieJar()

  5. # 创建opener

  6. opener = urllib.request.build_opener(

  7.    urllib.request.HTTPCookieProcessor(cj))

  8. # 给urllib.request安装opener

  9. urllib.request.install_opener(opener)

  10. # 请求

  11. request = urllib.request.Request('http://www.baidu.com/')

  12. response = urllib.request.urlopen(request)

  13. buff = response.read()

  14. html = buff.decode("utf8")

  15. print(html)

  16. print(cj)

网页解析器( BeautifulSoup )

从网页中提取出有价值的数据和新的 url 列表。

解析器选择

为了实现解析器,可以选择使用正则表达式、 html.parser 、 BeautifulSoup 、 lxml 等,这里我们选择 BeautifulSoup 。

其中,正则表达式基于模糊匹配,而另外三种则是基于 DOM 结构化解析。

BeautifulSoup

安装测试

1、安装,在命令行下执行 pip install beautifulsoup4 。 2、测试

  
  
  
  
  1. import bs4

  2. print(bs4)

使用说明

基本用法

1、创建 BeautifulSoup 对象

  
  
  
  
  1. import bs4

  2. from bs4 import BeautifulSoup

  3. # 根据html网页字符串创建BeautifulSoup对象

  4. html_doc = """

  5. The Dormouse's story

  6. The Dormouse's story

  7. Once upon a time there were three little sisters; and their names were

  8. Elsie,

  9. Lacie and

  10. Tillie;

  11. and they lived at the bottom of a well.

  12. ...

  13. """

  14. soup = BeautifulSoup(html_doc)

  15. print(soup.prettify())

2、访问节点

  
  
  
  
  1. print(soup.title)

  2. print(soup.title.name)

  3. print(soup.title.string)

  4. print(soup.title.parent.name)

  5. print(soup.p)

  6. print(soup.p['class'])

3、指定 tag 、 class 或 id

  
  
  
  
  1. print(soup.find_all('a'))

  2. print(soup.find('a'))

  3. print(soup.find(class_='title'))

  4. print(soup.find(id="link3"))

  5. print(soup.find('p', class_='title'))

4、从文档中找到所有 < a > 标签的链接

  
  
  
  
  1. for link in soup.find_all('a'):

  2.    print(link.get('href'))

出现了警告,根据提示,我们在创建 BeautifulSoup 对象时,指定解析器即可。

  
  
  
  
  1. soup = BeautifulSoup(html_doc, 'html.parser')

5、从文档中获取所有文字内容

  
  
  
  
  1. print(soup.get_text())

6、正则匹配

  
  
  
  
  1. link_node = soup.find('a', href=re.compile(r"til"))

  2. print(link_node)

后记

python 爬虫基础知识,至此足够,接下来,在实战中学习更高级的知识。


题图:pexels,CC0 授权。

点击阅读原文,查看更多 Python 教程和资源。



阅读原文:http://mp.weixin.qq.com/s?__biz=MzAwNDc0MTUxMw==&mid=2649639947&idx=1&sn=09780c2f4168aa1e7ba02e899d97d692&scene=0#wechat_redirect

你可能感兴趣的:(艺术人生经验 | Python爬虫基础)