运行环境:python3
BeautifulSoup4解析库
中文文档: https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
BeautifulSoup4 是 HTML/XML 的解析器,主要的功能便是解析和提取 HTML/XML 中的数据。
Python中用于爬取静态网页的基本方法/模块有三种:正则表达式、BeautifulSoup和Lxml。三种方法的特点大致如下:
beautifulSoup 的功能和 lxml 一样,但是 lxml 只会局部遍历数据,而 BeautifulSoup是基于HTML DOM的,所以会载入整个文档来解析整个DOM树。因此在性能上来说 BeautifulSoup 是低于lxml 的。
安装 BeautifulSoup4:
在 python3 中安装 BeautifulSoup4 的方法如下:
pip3 install beautifulsoup4
BeautifulSoup4使用
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐安装。
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('http://www.pythonscraping.com/pages/warandpeace.html')
bs = BeautifulSoup(html.read(), 'html.parser')
#bs.find_all(tagName, tagAttributes) 可以获取页面中所有指定的标签
nameList = bs.findAll('span', {
'class':'green'})
title = bs.body.h1
print(title)
head=bs.findAll(['h1','h2'])
print(head)
nameList1 = bs.find_all(text='the prince') #文本参数 text 有点不同,它是用标签的文本内容去匹配,而不是用标签的属性
print(len(nameList1))
for name in nameList:
print(name.get_text())
bs.find_all(tagName, tagAttributes) 可以获取页面中所有指定的标签
BeautifulSoup的find()和find_all()
BeautifulSoup 文档里两者的定义就是这样:
find_all(tag, attributes, recursive, text, limit, keywords)
find(tag, attributes, recursive, text, keywords)
正则表达式和BeautifulSoup
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
html = urlopen('http://www.pythonscraping.com/pages/page3.html')
bs = BeautifulSoup(html, 'html.parser')
images = bs.find_all('img',
{
'src': re.compile('\.\.\/img\/gifts\/img.*\.jpg')})
for image in images:
print(image['src'])
编写网络爬虫
全面彻底地抓取网站的常用方法是从一个顶级页面(比如主页)开始,然后搜索该页面上 的所有内链,形成列表。之后,抓取这些链接跳转到的每一个页面,再把在每个页面上找 到的链接形成新的列表,接着执行下一轮抓取。
1. 搜索维基百科上凯文 • 贝肯词条里所有指向其他词条的链接
-
一个函数 getLinks,可以用一个 /wiki/< 词条名称 > 形式的维基百科词条 URL 作为参数, 然后以同样的形式返回一个列表,里面包含所有的词条 URL。
-
一个主函数,以某个起始词条为参数调用 getLinks,然后从返回的 URL 列表里随机选 择一个词条链接,再次调用 getLinks,直到你主动停止程序,或者在新的页面上没有词 条链接了。
完整的代码如下所示:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import datetime
import random
import re
random.seed(datetime.datetime.now())
def getLinks(articleUrl):
html = urlopen('http://en.wikipedia.org{}'.format(articleUrl))
bs = BeautifulSoup(html, 'html.parser')
return bs.find('div', {
'id': 'bodyContent'}).find_all('a',
href=re.compile('^(/wiki/)((?!:).)*$'))
links = getLinks('/wiki/Kevin_Bacon')
while len(links) > 0:
newArticle = links[random.randint(0, len(links) - 1)].attrs['href']
print(newArticle)
links = getLinks(newArticle)
2.收集网站数据
通过观察几个维基百科页面,包括词条页面和非词条页面,比如隐私策略页 面,就会得出下面的规则。
-
所有的标题(所有页面上,不论是词条页面、编辑历史页面还是其他页面)都是在 h1 → span 标签里,而且页面上只有一个 h1 标签。
-
前面提到过,所有的正文文本都在 div#bodyContent 标签里。但是,如果我们只想获取 第一段文字,可能用 div#mw-content-text → p 更好(只选择第一段的标签)。这个规则 对所有内容页面都适用,除了文件页面(例如,https://en.wikipedia.org/wiki/File:Orbit_ of_274301_Wikipedia.svg),它们不包含内容文本(content text)部分。
-
编辑链接只出现在词条页面上。如果有编辑链接,都位于 li#ca-edit 标签的 li#ca- edit → span → a 里面。
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
pages = set()
def getLinks(pageUrl):
global pages
html = urlopen('http://en.wikipedia.org{}'.format(pageUrl))
bs = BeautifulSoup(html, 'html.parser')
try:
print(bs.h1.get_text())
print(bs.find(id='mw-content-text').find_all('p')[0])
print(bs.find(id='ca-edit').find('span')
.find('a').attrs['href'])
except AttributeError:
print("页面缺少一些属性!不过不用担心!")
for link in bs.find_all('a', href=re.compile('^(/wiki/)')):
if 'href' in link.attrs:
if link.attrs['href'] not in pages: # 我们遇到了新页面
newPage = link.attrs['href']
print('-' * 20)
print(newPage)
pages.add(newPage)
getLinks(newPage)
爬chakracore的label为bug的网址:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
pages = set()
def getLinks(pageUrl):
global pages
html = urlopen('https://github.com/chakra-core/ChakraCore/labels/Bug{}'.format(pageUrl))
bs = BeautifulSoup(html, 'html.parser')
for link in bs.find_all('a', href=re.compile('^(\/chakra-core\/ChakraCore\/issues\/)[0-9]+')):
if 'href' in link.attrs:
if link.attrs['href'] not in pages: # 我们遇到了新页面
newPage = link.attrs['href']
print('-' * 20)
print(newPage)
pages.add(newPage)
getLinks(newPage)
getLinks('')
Scrapy
1.安装Scrapy:
conda install -c conda-forge scrapy
-
一个蜘蛛(spider)就是一 个 Scrapy 项目,和它的名称一样,就是用来爬网(抓取网页)的
-
“爬虫”(crawler)表示“任意用或不用 Scrapy 抓取网页的程序”
https://scrapy-chs.readthedocs.io/zh_CN/0.24/intro/tutorial.html
2.编写第一个爬虫(Spider)
Spider是用户编写用于从单个网站(或者一些网站)爬取数据的类。
其包含了一个用于下载的初始URL,如何跟进网页中的链接以及如何分析页面中的内容, 提取生成 item 的方法。
为了创建一个Spider,您必须继承 scrapy.Spider
类, 且定义以下三个属性:
name
: 用于区别Spider。 该名字必须是唯一的,您不可以为不同的Spider设定相同的名字。start_urls
: 包含了Spider在启动时进行爬取的url列表。 因此,第一个被获取到的页面将是其中之一。 后续的URL则从初始的URL获取到的数据中提取。parse()
是spider的一个方法。 被调用时,每个初始URL完成下载后生成的Response
对象将会作为唯一的参数传递给该函数。 该方法负责解析返回的数据(response data),提取数据(生成item)以及生成需要进一步处理的URL的Request
对象。
创建项目
在开始爬取之前,您必须创建一个新的Scrapy项目。 进入您打算存储代码的目录中,运行下列命令:
scrapy startproject tutorial
该命令将会创建包含下列内容的 tutorial
目录:
tutorial/
scrapy.cfg
tutorial/
__init__.py
items.py
pipelines.py
settings.py
spiders/
__init__.py
...
这些文件分别是:
scrapy.cfg
: 项目的配置文件tutorial/
: 该项目的python模块。之后您将在此加入代码。tutorial/items.py
: 项目中的item文件.tutorial/pipelines.py
: 项目中的pipelines文件.tutorial/settings.py
: 项目的设置文件.tutorial/spiders/
: 放置spider代码的目录.
定义Item
Item 是保存爬取到的数据的容器;其使用方法和python字典类似, 并且提供了额外保护机制来避免拼写错误导致的未定义字段错误。
提取Item
Selectors选择器简介
从网页中提取数据有很多方法。Scrapy使用了一种基于 XPath 和 CSS 表达式机制: Scrapy Selectors 。 关于selector和其他提取机制的信息请参考 Selector文档 。
这里给出XPath表达式的例子及对应的含义:
/html/head/title
: 选择HTML文档中<head>
标签内的<title>
元素/html/head/title/text()
: 选择上面提到的<title>
元素的文字//td
: 选择所有的<td>
元素//div[@class="mine"]
: 选择所有具有class="mine"
属性的div
元素
为了配合XPath,Scrapy除了提供了 Selector
之外,还提供了方法来避免每次从response中提取数据时生成selector的麻烦。
Selector有四个基本的方法(点击相应的方法可以看到详细的API文档):