爬虫期末复习

695次阅读
没有评论

1.常见大数据来源

社交媒体、社交网络、百科知识库、新闻网站、评论信息、位置型信息

2.大数据采集技术的重要性

(1)若干个重要环节,包括数据采集、结构化处理、数据存储、分析挖掘、可视化、共享交易等;

(2)大数据采集处于整个架构的底层,是整个架构的基础;

(3)大数据采集技术性能的好坏直接影响到数据采集的效率和数据的质量。

3.Python语言生态

(1)开源软件和插件

(2)涵盖科学计算、语言处理、文本挖掘、图像处理等等

(3)选择Python语言进行互联网大数据采集技术的实现具有一定实际意义和必要性

4.爬虫技术应用场景

采集型、监测型

5.什么是采集和监测爬虫

采集型爬虫的典型使用场景包括互联网搜索引擎、互联网舆情监测、社交媒体评论信息监测、学术论文采集、离线浏览;

监测型爬虫的典型使用场景包括应用安全监测、网页挂马、SQL注入 、内容安全监测、敏感信息、泄密信息。

6.法律与技术边界

互联网公开资源爬取并不违法,网络爬虫作为互联网大数据采集的技术手段,本身具有中立性。而抓取没有权限、没有授权的数据,对服务器正常运行产生影响,以及抓取后的数据用于商业用途、未经授权公开展示,应该是突破了爬虫大数据采集的边界。

7.编码体系与规范

(1)国内常见的网页字符编码主要有utf-8、gbk、gb2312,其中utf-8为国际化编码;

(2)Unicode是Python默认编码;

(3)utf-8/gbk/gb2312之间的转换(填空):在python中,使用encode()将unicode编码为utf-8、gbk等,而使用decode()将utf-8、gbk等字符编码解码为unicode;

>>> n=’大数据’                        #unicode

>>> g=n.encode(‘gbk’)                 #gbk

>>> u=n.encode(‘utf-8’)               #utf-8

>>> g2=n.encode(‘gb2312’)             #gb2312

>>> g2u=g.decode(“gbk”).encode(“utf-8”)   #gbk转成utf-8

(4)BeautifulSoup将输出文档自动转换成utf-8编码。

8.正则表达式(findall、match从头开始匹配、soup、search)——重点

re模块提供了正则表达式匹配所需要的功能:匹配和搜索、分割字符串、匹配和替换。

9.Web服务器的应用架构

(1)四种经典架构:Client/Server、Client/Server/Database、Web服务器集群、虚拟主机架构

(2)web页面类型:静态页面(以html文件的形式存在于Web服务器的硬盘上)、动态页面(需要数据库等其他计算、存储服务的支持)、伪静态页面(以静态页面展现出来,但实际上是用动态脚本来处理的)。

10.Robots协议的定义及如何获取

Robots协议又称为爬虫协议、机器人协议等,其全称是Robots Exclusion Protocol,即“网络爬虫排除协议”。在浏览器中打开网站后,在网站首页的地址后面添加“/robots.txt”,如果网站设置了访问许可,按回车就可以看到网站的robots协议,即robots.txt文件内容。

11.http协议(基本原理(URI标志和URL定位))

URI 的全称为 Uniform Resource Identifier,即统一资源标志符;而 URL 的全称为 Universal Resource Locator,即统一资源定位符。URN的全称为 Universal Resource Name,即统一资源名称。

12.URI.URL.URN之间的关系

URL 是 URI 的子集,URN是URI 的一个子类

13.URL的格式(选择/填空)

scheme://[username:password@]hostname[:port][/path][;parameters][?query][#fragment]

scheme:协议,比如常用的协议有 http、https、ftp 等

username、password:用户名和密码

hostname:主机地址。可以是域名或 IP 地址

port:端口

path:路径,指的是网络资源在服务器中的指定地址

parameters:参数,用来制定访问某个资源的时候的附加信息

query:查询

fragment:片段。它是对资源描述的部分补充,可以理解为资源内部的书签。

14.http和HTTPS之间的区别

HTTP 的全称是 Hyper Text Transfer Protocol,中文名叫作超文本传输协议。HTTP 协议是用于从网络传输超文本数据到本地浏览器的传送协议,它能保证高效而准确地传送超文本文档。HTTPS 的全称是 Hyper Text Transfer Protocol over Secure Socket Layer,是以安全为目标的 HTTP 通道,简单讲是 HTTP 的安全版,即在 HTTP 下加入 SSL 层,简称为 HTTPS。HTTPS 的安全基础是 SSL,因此通过它传输的内容都是经过 SSL 加密的。

15.get和post的区别(简答)

常见的请求方法有两种:GET 和 POST。

GET 请求中的参数包含在 URL 里面,数据可以在 URL 中看到;而 POST 请求的 URL 不会包含这些数据,数据都是通过表单形式传输的,会包含在请求体中。

GET 请求提交的数据最多只有 1024 字节,而 POST 方式没有限制。

16.cookie和session之间的关系(客户端cookie、服务器session)

Session 在服务端,也就是网站的服务器,用来保存用户的 Session 信息;Cookie 在客户端,也可以理解为浏览器端,有了 Cookie,浏览器在下次访问网页时会自动附带上它发送给服务器,服务器通过识别 Cookie 并鉴定出是哪个用户,然后再判断用户是否是登录状态,然后返回对应的响应。

17.发送请求URLopen的参数和方法request等

(1)利用 urlopen 方法可以实现最基本请求的发起,利用它可以模拟浏览器的一个请求发起过程。

urllib.request.urlopen(url, data=None, [timeout,]*, cafile=None, capath=None, cadefault=False, context=None)

data 参数是可选的。如果要添加该参数,需要使用 bytes 方法将参数转化为字节流编码格式的内容,即 bytes 类型。另外,如果传递了这个参数,则它的请求方式就不再是 GET 方式,而是 POST 方式。

timeout 参数用于设置超时时间,单位为秒,意思就是如果请求超出了设置的这个时间,还没有得到响应,就会抛出异常。

context 参数必须是 ssl.SSLContext 类型,用来指定 SSL 设置。

cafile 和 capath 这两个参数分别指定 CA 证书和它的路径,这个在请求 HTTPS 链接时会有用。

(2)urllib.request.Request(url,data=None,headers={},origin_req_host=None,unverifiable=False,

method=None)

url :用于请求 URL,这是必传参数,其他都是可选参数。

data: 如果要传,必须传 bytes(字节流)类型的。如果它是字典,可以先用 urllib.parse 模块里的 urlencode() 编码。

 headers: 是一个字典,它就是请求头。我们在构造请求时,既可以通过 headers 参数直接构造,也可以通过调用请求实例的 add_header() 方法添加。

origin_req_host: 请求方的 host 名称或者 IP 地址。

unverifiable :表示这个请求是否是无法验证的,默认是 False,意思就是说用户没有足够权限来选择接收这个请求的结果。例如,我们请求一个 HTML 文档中的图片,但是我们没有自动抓取图像的权限,这时 unverifiable 的值就是 True。

Method: 用来指示请求使用的方法,比如 GET、POST 和 PUT 等。

18.异常处理(掏空代码填空)

urllib 的 error 模块定义了由 request 模块产生的异常。如果出现了问题,request 模块便会抛出 error 模块中定义的异常。

from urllib import request, error

try:

response = request.urlopen(‘https://www.baidu.com/404’)

except error.URLError as e:

print(e.reason)

from urllib import request, error

try:

response = request.urlopen(‘https://www.baidu.com/404′)

except error.HTTPError as e:

print(e.reason, e.code, e.headers, sep=’\n’)

from urllib import request, error

try:

response = request.urlopen(‘https://www.baidu.com/404′)

except error.HTTPError as e:

print(e.reason, e.code, e.headers, sep=’\n’)

except error.URLError as e:

print(e.reason)

else:

print(‘Request Successfully’)

19.解析链接

urlparse方法可以实现 URL 的识别和分段。

from urllib.parse import urlparse

result = urlparse(‘https://www.baidu.com/index.html;user?id=5#comment’)

print(type(result))

print(result)

运行结果:

<class ‘urllib.parse.ParseResult’>

ParseResult(scheme=’https’, netloc=’www.baidu.com’, path=’/index.html’, params=’user’, query=’id=5′, fragment=’comment’)

标准链接格式:scheme://netloc/path;params?query#fragment

:// 前面的就是 scheme,代表协议;第一个 / 符号前面便是 netloc,即域名,后面是 path,即访问路径;分号 ; 后面是 params,代表参数;问号 ? 后面是查询条件 query,一般用作 GET 类型的 URL;井号 # 后面是锚点,用于直接定位页面内部的下拉位置。

20.xpath、beautifulsoup

(1)xpath

①XPath:在XML、HTML文档中查找信息的语言。

②nodename:选取此节点的所有子节点

   /:从当前节点选取直接子节点

   //:从当前节点选取子孙节点

   .:选取当前节点

   ..:选取当前节点的父节点

   @:选取属性

③安装lxml:pip install lxml

④示例如下

爬虫期末复习

解析:文本最后一个li节点没有闭合,但是etree可以自动修正;调用tostring即可输出bytes型的修正后的HTML代码,decode方法可将其转成str类型。

⑤可以直接读取文本文件进行解析

html=etree.parse(‘./test.html’,etree.HTMLParser())

result = etree.tostring(html)

print(result.decode(‘utf-8’))

输出结果:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

<html><body><div>

  <ul>

    <li class="item-0"><a href="link1.html">first item</a></li>

    <li class="item-1"><a href="link2.html">second item</a></li>

    <li class="item-inactive"><a href="link3.html">third item</a></li>

    <li class="item-1"><a href="link4.html">fourth item</a></li>

    <li class="item-0"><a href="link5.html">fifth item</a></li>

  </ul>

</div></body></html>

 

⑥用//开头的XPath规则来选取所有符合要求的节点,返回元素类型是element的列表。

(1)

result=html.xpath(‘//*’);//* 代表匹配所有节点

print(result)

 

输出结果:

[<Element html at 0x10510d9c8>, <Element body at 0x10510da08>, <Element div at 0x10510da48>, <Element ul at 0x10510da88>, <Element li at 0x10510dac8>, <Element a at 0x10510db48>, <Element li at 0x10510db88>, <Element a at 0x10510dbc8>, <Element li at 0x10510dc08>, <Element a at 0x10510db08>, <Element li at 0x10510dc48>, <Element a at 0x10510dc88>, <Element li at 0x10510dcc8>, <Element a at 0x10510dd08>](2)

(2)

result = html.xpath(‘//li’);//指定节点名称

print(result)

print(result[0])

输出结果:

[<Element li at 0x105849208>, <Element li at 0x105849248>, <Element li at 0x105849288>, <Element li at 0x1058492c8>, <Element li at 0x105849308>]

<Element li at 0x105849208>

(3)通过 / 或 // 即可当前节点的所有直接子节点或子孙节点

result = html.xpath(‘//li/a’);//直接子节点 result = html.xpath(‘//ul//a’);//子孙节点

输出结果:

[<Element a at 0x106ee8688>, <Element a at 0x106ee86c8>, <Element a at 0x106ee8708>, <Element a at 0x106ee8748>, <Element a at 0x106ee8788>]

⑦用..或parent::查找父节点

result=html.xpath(‘//a[@href=”link4.html”]/..’)

result=html.xpath(‘//a[@href=”link4.html”]/parent::*’)

输出结果:[‘item-1’]

⑧用@可以进行属性过滤

result = html.xpath(‘//li[@class=”item-0″]’)

输出结果:

<Element li at 0x10a399288>, <Element li at 0x10a3992c8>

⑨用@获取节点属性

result = html.xpath(‘//li/a/@href’)

输出结果:[‘link1.html’, ‘link2.html’, ‘link3.html’, ‘link4.html’, ‘link5.html’](用的10的例子)

⑩用test获取节点中的文本

test='''

<div>

  <ul>

    <li class="item-0"><a href="link1.html">first item</a>99</li>

    <li class="item-1"><a href="link2.html">second item</a></li>

    <li class="item-inactive"><a href="link3.html">third item</a></li>

    <li class="item-1"><a href="link4.html">fourth item</a></li>

    <li class="item-0"><a href="link5.html">fifth item</a>88</li>

  </ul>

</div>
'''

from lxml import etree

html = etree.parse('./test.html', etree.HTMLParser())

result = html.xpath('//li[@class="item-0"]/text()')

print(result)

 

输出结果:[’99’, ’88‘]

⑩①可以直接使用//加test方法获取子孙节点内部的所有文本

result = html.xpath(‘//li[@class=”item-0″]//text()’)

输出结果:[‘first item’, ’98’, ‘fifth item’, ’88’]

⑩②属性多值匹配

result = html.xpath(‘//li[contains(@class, “li”)]/a/text()’)

输出结果:[‘first item’]

⑩③利用中括号传入索引的方法获取特定次序的节点

test='''

<div>

  <ul>

    <li class="item-0"><a href="link1.html">first item</a>99</li>

    <li class="item-1"><a href="link2.html">second item</a></li>

    <li class="item-inactive"><a href="link3.html">third item</a></li>

    <li class="item-1"><a href="link4.html">fourth item</a></li>

    <li class="item-0"><a href="link5.html">fifth item</a>88</li>

  </ul>

</div>
'''

from lxml import etree

html = etree.parse('./test.html', etree.HTMLParser())

result = html.xpath('//li[@class="item-0"]/text()')

print(result)

 

html = etree.HTML(text)

result = html.xpath(‘//li[1]/a/text()’)

print(result)

result = html.xpath(‘//li[last()]/a/text()’)

print(result)

result = html.xpath(‘//li[position()<3]/a/text()’)

print(result)

result = html.xpath(‘//li[last()-2]/a/text()’)

print(result)

输出结果:

[‘first item’]

[‘fifth item’]

[‘first item’, ‘second item’]

[‘third item‘]

(2)BeautifulSoup

①基本用法

html = “”” <html><head><title>The Dormouse’s story</title></head> <body> <p class=”title” name=”dromouse”><b>The Dormouse’s story</b></p> <p class=”story”>Once upon a time there were three little sisters; and their names were <a href=”http://example.com/elsie” class=”sister” id=”link1″><!– Elsie –></a>, <a href=”http://example.com/lacie” class=”sister” id=”link2″>Lacie</a> and <a href=”http://example.com/tillie” class=”sister” id=”link3″>Tillie</a>; and they lived at the bottom of a well.</p> <p class=”story”>…</p> “”” from bs4 import BeautifulSoup soup = BeautifulSoup(html, ‘lxml’) print(soup.prettify()) print(soup.title.string)

运行结果:

<html>

 <head>

  <title>

   The Dormouse’s story

  </title>

 </head>

 <body>

  <p class=”title” name=”dromouse”>

   <b>

    The Dormouse’s story

   </b>

  </p>

  <p class=”story”>

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

   <a class=”sister” href=”http://example.com/elsie” id=”link1″>

    <!– Elsie –>

   </a>

   ,

   <a class=”sister” href=”http://example.com/lacie” id=”link2″>

    Lacie

   </a>

   and

   <a class=”sister” href=”http://example.com/tillie” id=”link3″>

    Tillie

   </a>

   ;

and they lived at the bottom of a well.

  </p>

  <p class=”story”>

   …

  </p>

 </body>

</html>

The Dormouse’s story

②调用 prettify() 方法,可以把要解析的字符串以标准的缩进格式输出

③获取内容:<html><head><title>The Dormouse’s story</title></head>

print(soup.p.string)

得到The Dormouse’s story。

④获取节点的名称:

print(soup.title.name)

⑤获取节点属性:

print(soup.p.attrs); print(soup.p.attrs[‘name’]); print(soup.p[‘name’]);

输出结果:

{‘class’: [‘title’], ‘name’: ‘dromouse’}

dromouse

dromouse

⑥嵌套选择:

print(soup.head.title.string)

调用 head 来选取其内部的 head 节点元素

⑦选取节点元素之后,如果想要获取它的直接子节点,可以调用 contents 属性

html = “”” <html> <head> <title>The Dormouse’s story</title> </head> <body> <p class=”story”> Once upon a time there were three little sisters; and their names were <a href=”http://example.com/elsie” class=”sister” id=”link1″> <span>Elsie</span> </a> <a href=”http://example.com/lacie” class=”sister” id=”link2″>Lacie</a> and <a href=”http://example.com/tillie” class=”sister” id=”link3″>Tillie</a> and they lived at the bottom of a well. </p> <p class=”story”>…</p> “””

from bs4 import BeautifulSoup soup=BeautifulSoup(html,’lxml’) print(soup.p.contents)

输出结果:<span>Elsie</span>

调用 children 属性得到相应的结果:

print(soup.p.children);

for i, child in enumerate(soup.p.children):

print(i, child);

⑧得到所有的子孙节点的话,可以调用 descendants 属性:

print(soup.p.descendants) for i, child in enumerate(soup.p.descendants): print(i, child)

遍历输出:

<generator object Tag.descendants at 0x000001CFA9D45E40>

0

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

1 <a class=”sister” href=”http://example.com/elsie” id=”link1″>

<span>Elsie</span>

</a>

2

3 <span>Elsie</span>

4 Elsie

5

6

7 <a class=”sister” href=”http://example.com/lacie” id=”link2″>Lacie</a>

8 Lacie

9

            and

10 <a class=”sister” href=”http://example.com/tillie” id=”link3″>Tillie</a>

11 Tillie

12

            and they lived at the bottom of a well.

⑨获取某个节点元素的直接父节点,可以调用 parent 属性:

print(soup.a.parent);

输出结果:

<p class=”story”>

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

            <a class=”sister” href=”http://example.com/elsie” id=”link1″><span>Elsie</span>

</a>

</p>

⑩获取所有的祖先节点

print(list(enumerate(soup.a.parents)));

⑩①获取兄弟节点

print(‘Next Sibling’, soup.a.next_sibling);//获取节点的下一个兄弟元素 print(‘Prev Sibling’, soup.a.previous_sibling);//获取节点的上一个兄弟元素 print(‘Next Siblings’, list(enumerate(soup.a.next_siblings)));//返回所有前面的兄弟节点的生成器 print(‘Prev Siblings’, list(enumerate(soup.a.previous_siblings)));//返回所有后面的兄弟节点的生成器

输出结果:

Next Sibling

            Hello

Prev Sibling

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

Next Siblings [(0, ‘\n            Hello\n            ‘), (1, <a class=”sister” href=”http://example.com/lacie” id=”link2″>Lacie</a>), (2, ‘ \n            and\n            ‘), (3, <a class=”sister” href=”http://example.com/tillie” id=”link3″>Tillie</a>), (4, ‘\n            and they lived at the bottom of a well.\n        ‘)]

Prev Siblings [(0, ‘\n            Once upon a time there were three little sisters; and their names were\n            ‘)]

⑩②

print(list(soup.a.parents)[0]);

输出结果:

<p class=”story”>

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

            <a class=”sister” href=”http://example.com/elsie” id=”link1″>Bob</a><a class=”sister” href=”http://example.com/lacie” id=”link2″>Lacie</a>

</p>

⑩③find_all(),查询所有符合条件的元素,返回一个列表

html=”’ <div class=”panel”> <div class=”panel-heading”> <h4>Hello</h4> </div> <div class=”panel-body”> <ul class=”list” id=”list-1″> <li class=”element”>Foo</li> <li class=”element”>Bar</li> <li class=”element”>Jay</li> </ul> <ul class=”list list-small” id=”list-2″> <li class=”element”>Foo</li> <li class=”element”>Bar</li> </ul> </div> </div> ”’ from bs4 import BeautifulSoup soup = BeautifulSoup(html, ‘lxml’)

(1)

print(soup.find_all(name=’ul’));

输出结果:

[<ul class=”list” id=”list-1″>

<li class=”element”>Foo</li>

<li class=”element”>Bar</li>

<li class=”element”>Jay</li>

</ul>, <ul class=”list list-small” id=”list-2″>

<li class=”element”>Foo</li>

<li class=”element”>Bar</li>

</ul>]

(2)

for ul in soup.find_all(name=’ul’): print(ul.find_all(name=’li’)); for li in ul.find_all(name=’li’): print(li.string);

输出结果:

[<li class=”element”>Foo</li>, <li class=”element”>Bar</li>, <li class=”element”>Jay</li>]

Foo

Bar

Jay

[<li class=”element”>Foo</li>, <li class=”element”>Bar</li>]

Foo

Bar

(3)

print(soup.find_all(attrs={‘id’: ‘list-1’}));

输出结果:

[<ul class=”list” id=”list-1″ >

<li class=”element”>Foo</li>

<li class=”element”>Bar</li>

<li class=”element”>Jay</li>

</ul>]

(4)

import re html=”’ <div class=”panel”> <div class=”panel-body”> <a>Hello, this is a link</a> <a>Hello, this is a link, too</a> </div> </div> ”’ from bs4 import BeautifulSoup soup = BeautifulSoup(html, ‘lxml’) print(soup.find_all(text=re.compile(‘link’)))

输出结果:[‘Hello, this is a link’, ‘Hello, this is a link, too’]

⑩④find() 方法返回的是单个元素,也就是第一个匹配的元素

print(soup.find(name=’ul’));

输出结果:

<ul class=”list” id=”list-1″>

<li class=”element”>Foo</li>

<li class=”element”>Bar</li>

<li class=”element”>Jay</li>

</ul>

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python教程2022-10-24发表,共计13688字。
新手QQ群:570568346,欢迎进群讨论 Python51学习