脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python爬虫技术

Python爬虫技术

2021-12-23 00:28无药可医 Python

本文将要介绍的是python爬虫基础知识,感兴趣的小伙伴一起来学习吧

一、python爬虫简单介绍

1、抓取网页本身的接口

 Python爬虫技术

相比与其他静态的编程语言,如java,c#,c++,python抓取网页的接口更简洁;相比其他动态脚本语言,如perl,shell,python的urllib包提供了较为完整的访问网页文档的api。(当然ruby也是很好的选择)此外,抓取网页有时候需要模拟游览器的行为,很多网站对于生硬的爬虫抓取都是封杀的。这是我们需要模拟user agen的行为构造合适的请求,譬如模拟用户登录、模拟session/cookie的存蓄和设置。在python里都有非常优秀的第三方包帮你搞定,如request,mechanize。

2、网页抓取后的处理

抓取的网页通常需要处理,比如过滤html标签,提取文本等。python的beautiulsoap提供了简洁的文档处理功能,能用极短的代码完成大部分文档的处理。
其实以上功能很多的语言都能做,但是用python能够干得最快,最干净。

?
1
life is short, you need python.

ps:python2.x和python3.x有很大不同,本文先讨论python3.x的爬虫实现方法。

二、爬虫架构

架构组成
url管理器:管理待爬的url集合好已爬取的url集合,传送待爬的url给网页下载器。
网页下载器(urllib):爬取url对应的网页你,存蓄成字符串,传送给网页解析器。
网页解析器(beautifulsoap):解析出有价值的数据,存蓄下来,同时补充url到url管理器。
 

三、url管理器

1、基本功能

添加新的url到爬取url集合中。
判断待添加的url是否在容器中(包括待爬取url集合和已爬取的url集合)。
获取待爬取的url。
判断是否有待爬取的url。
将爬取完成的url从待爬取的url集合移动到已爬取url集合。

2、存蓄方式

内存(python内存)
待爬取url集合:set()
已爬取url集合:set()
关系数据库(mysql)
urls(url,is_crawled)
缓存(redis)
待爬取url集合:set
已爬取url集合:set
大型互联网公司,由于缓存数据库的高性能,一般把url存蓄在缓存数据库中。小型公司,一般把url存蓄在内存中,如果想要永存存蓄,则存蓄到关系数据库中。

3、网页下载器(urllib)

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

基本方法
新建baidu.py,内容如下:

?
1
2
3
4
5
6
7
import urllib.request
 
response = urllib.request.urlopen('http://www.baidu.com')
buff = response.read()
html = buff.decode("utf8")
print(html)
命令行中执行python baidu.py,则可以打印出获取到的网页。

构造request:

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

?
1
2
3
4
5
6
7
import urllib.request
 
request = urllib.request.request('http://www.baidu.com')
response = urllib.request.urlopen(request)
buff = response.read()
html = buff.decode("utf8")
print(html)

携带参数:
新建baidu2.py,内容如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
import urllib.request
import urllib.parse
 
url = 'http://www.baidu.com'
values = {'name': 'voidking','language': 'python'}
data = urllib.parse.urlencode(values).encode(encoding='utf-8',errors='ignore')
headers = { 'user-agent' : 'mozilla/5.0 (windows nt 10.0; wow64; rv:50.0) gecko/20100101 firefox/50.0' }
request = urllib.request.request(url=url, data=data,headers=headers,method='get')
response = urllib.request.urlopen(request)
buff = response.read()
html = buff.decode("utf8")
print(html)

使用fiddler监听数据:

我们想要查看一下,我们的请求是否真的携带了参数,所以需要使用fiddler。
打开fiddler之后,却意外发现,上面的代码会报错504,无论是baidu.py还是baidu2.py。
虽然python有报错但是在fiddler中,我们可以看到请求信息,确实携带了参数。
经过寻找资料,发现python以前版本的request都不支持代理环境下访问https。但是,最近的版本应该支持了才对。那么,最简单的办法,就是换一个使用http协议的url来爬取,把http://www.baidn.com改成http://www.baidu.com/,请求成功了!神奇!!!

添加处理器:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import urllib.request
import http.cookiejar
 
# 创建cookie容器
cj = http.cookiejar.cookiejar()
# 创建opener
opener = urllib.request.build_opener(urllib.request.httpcookieprocessor(cj))
# 给urllib.request安装opener
urllib.request.install_opener(opener)
 
# 请求
request = urllib.request.request('http://www.baidu.com/')
response = urllib.request.urlopen(request)
buff = response.read()
html = buff.decode("utf8")
print(html)
print(cj)

四、网页解析器(beautifulsoup)

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

1、解析器选择

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

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

2、beautifulsoup

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

(2)测试。

?
1
2
import bs4
print(bs4)

3、使用说明

创建beautifulsoup对象:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import bs4
from bs4 import beautifulsoup
 
# 根据html网页字符串创建beautifulsoup对象
html_doc = """
<html><head><title>the dormouse's story</title></head>
<body>
<p class="title"><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://www.zzvips.com/bc/" class="sister" id="link1">elsie</a>,
<a href="http://www.zzvips.com/bc/" class="sister" id="link2">lacie</a> and
<a href="http://www.zzvips.com/bc/" class="sister" id="link3">tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = beautifulsoup(html_doc)
print(soup.prettify())

访问节点;

?
1
2
3
4
5
6
7
print(soup.title)
print(soup.title.name)
print(soup.title.string)
print(soup.title.parent.name)
 
print(soup.p)
print(soup.p['class'])

指定tag、class或id:

?
1
2
3
4
5
print(soup.find_all('a'))
print(soup.find('a'))
print(soup.find(class_='title'))
print(soup.find(id="link3"))
print(soup.find('p',class_='title'))

从文档中找到所以<a>标签的链接:

?
1
2
for link in soup.find_all('a'):
    print(link.get('href'))

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

?
1
soup = beautifulsoup(html_doc,'html.parser')

从文档中获取所以文字内容:

?
1
print(soup.get_text())

正则匹配:

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

到此这篇关于python爬虫技术的文章就介绍到这了,更多相关python爬虫内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/m0_60636930/article/details/119807470

延伸 · 阅读

精彩推荐