爬虫的介绍
网络爬虫(web crawler 又称网页蜘蛛,网络机器人,在FOAF社区中间称为网页追逐者),是一种按照一定的规定,自动的抓取万维网信息的程序或者脚本。
爬虫产生的背景
随着网络的发展,万维网成为大量的信息载体,如何有效的提取并利用这些信息成为巨大挑战。
搜索引擎作为一个辅助人们检索信息的工具成为用户访问万维网的入口和指南,但同时通用性的搜索引擎存在一定的局限性。
- 不同领域、不同背景的用户具有不同的检索目的和需求,通过搜索引擎所返回的结果包含大量用户不关心的网页。
- 通过搜索引擎的目标是尽可能大的网络覆盖率,有限的搜索引擎服务器资源与无限的网络数据资源之间的矛盾将进一步加深。
- 万维网数据形式的丰富和网络技术的不断发展,图片、数据库、音频、视频多媒体等不同数据大量出现,通用性搜索引擎往往对这些信息含量密集且具有一定结构的数据无能为力,不能很好的发现和获取。
- 通用搜索引擎大多提供基于关键字的检索,难以支持根据语义信息提出的查询。
为解决上述问题,定向抓取相关网页资源的聚焦爬虫应运而生。聚焦爬虫是一个自动下载网页的程序,他根据既定的抓取目标,有选择的访问万维网上的网页与相关的链接,获取所需要的信息。
python实现HTTP请求
爬虫的必备功能:读取url、下载网页。在python中实现HTTP请求有三种方法:
- urllib2/urllib
- httplib/urllib
- Requests
例子 bilibili
import requests
from bs4 import BeautifulSoup
import pprint
import json
def download_html():
htmls = []
url = "https://www.bilibili.com/read/lightnovel?from=category_0"
print("craw html:", url)
response = requests.get(url=url)
if response.status_code != 200:
raise Exception("error")
htmls.append(response.text)
return htmls
def parse_single_html(hml):
""" retrun list({link},title)"""
soup = BeautifulSoup(hml, "html.parser")
articles = soup.find_all(attrs={'class': 'item'})
datas = []
for article in articles:
title_node = (article.find(name='a'))
title = title_node["title"]
link = title_node["href"]
datas.append({"title": title, "link": link})
return datas
all_datas = []
for html in download_html():
all_datas.append(parse_single_html(html))
pprint.pprint(all_datas)