爬虫

爬虫

网络爬虫又称网络蜘蛛、网络机器人,它是一种按照一定的规则自动浏览、检索网页信息的程序或者脚本。网络爬虫能够自动请求网页,并将所需要的数据抓取下来。通过对抓取的数据进行处理,从而提取出有价值的信息。

简易的爬虫程序

下面使用 Python 内置的 urllib 库获取网页的 html 信息。注意,urllib 库属于 Python 的标准库模块,无须单独安装,它是 Python 爬虫的常用模块。

1
2
3
4
5
6
7
8
9
from urllib import request

# 发送请求,获取响应对象
response = request.urlopen('http://www.baidu.com/')
print(response)
# 提取响应内容,再将字节码解码成字符串
html = response.read().decode('utf-8')
# 打印响应内容
print(html)

防反爬措施1

绝大多数网站都具备一定的反爬能力,禁止爬虫大量地访问网站,以免给网站服务器带来压力。
网站通过识别请求头中 User-Agent 信息来判断是否是爬虫访问网站。如果是,网站首先对该 IP 进行预警,对其进行重点监控,当发现该 IP 超过规定时间内的访问次数, 将在一段时间内禁止其再次访问网站。
下面我们通过修改 User-Agent 信息来防反爬。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 导包
from urllib import request

# 目标url
url = 'https://tieba.baidu.com/f/search/res?ie=utf-8&qw=python'
# 重构请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763'}
# 创建请求对象,包装ua信息
req = request.Request(url=url, headers=headers)
# 发送请求,获取响应对象
res = request.urlopen(req)

# 返回响应对象的URL地址
url = res.geturl()
print("\n目标url:", url)

# 返回请求时的HTTP响应码
code = res.getcode()
print("状态码:", code)

# 提取响应内容,再将字节码解码成字符串
html = res.read().decode('utf-8')
print(html)

防反爬措施2

通过调用自定义UA池的UA标识来修改 User-Agent 信息防反爬。
main.py

1
2
3
from ua_info import ua_list  # 使用自定义的ua池
import random
headers={'User-Agent': random.choice(ua_list)}

ua_info.py

1
2
3
4
5
6
7
8
9
10
11
12
ua_list = [
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
'User-Agent:Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',
'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0',
' Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1',
' Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
]

防反爬措施3

爬虫程序访问网站会非常快,这与正常人类的点击行为非常不符。因此,通过随机休眠可以使爬虫程序模仿成人类的样子点击网站,从而让网站不易察觉是爬虫访问网站,但这样做的代价就是影响程序的执行效率。

1
2
3
4
# 每爬取一个页面随机休眠1-2秒钟的时间
import time
import random
time.sleep(random.randint(1, 2))

Requests库

Requests 库是在 urllib 的基础上开发而来,它使用 Python 语言编写,并且采用了 Apache2 Licensed(一种开源协议)的 HTTP 库。与 urllib 相比,Requests 更加方便、快捷,因此在编写爬虫程序时 Requests 库使用较多。
每次调用 requests 请求之后,会返回一个 response 对象,该对象包含了具体的响应信息。

下面使用 requests 的 GET 请求并查看返回对象部分的响应信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 导入 requests 包
import requests

# 目标url
url = 'http://baidu.com'
# 发送请求,返回一个响应对象response
response = requests.get(url)

# 响应对象
print("\n响应对象:", response)

# 响应对象的状态码
print("状态码:", response.status_code)
# 响应对象的响应状态描述
print("响应状态描述:", response.reason)
# 响应对象的编码
print("编码:", response.apparent_encoding)

# 调用响应对象text属性,获取文本信息
print(response.text)

下面使用 requests 的 GET 请求爬取百度搜索的页面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import requests
headers={
'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Mobile Safari/537.36'
}
url='https://www.baidu.com/s'
content = input('请输入您想查询的词:')
# 通过字典赋予get请求参数
param = {
'wd':content,
'pn':0
}
# 此get()方法使用了三个参数
response = requests.get(url=url, params=param, headers=headers)
html = response.text

with open('百度.html', 'w', encoding='utf-8') as df:
df.write(html)
print('保存成功')

requests中的 post() 方法还可以发送 POST 请求到指定 url

1
requests.post(url, data={key: value}, json={key: value}, args)

re库

见参考

Beautiful Soup库

见参考

爬虫编写思路

1.确定页面类型
查看页面源码,确定要抓取的数据是否存在于页面内。通过浏览得知要抓取的信息全部存在于源码内,因此该页面输属于静态页面。
2.确定url规律
想要确定 url 规律,需要您多浏览几个页面,然后才可以总结出 url 规律。
3.发送测试请求
向目标网址发送测试请求,查看返回对象的状态码,确定该页码是否可爬,下面以百度为例

1
2
3
4
5
6
7
8
9
# 导入 requests 包
import requests

# 目标url
url = 'http://baidu.com'
# 发送请求,返回一个响应对象response
response = requests.get(url)
# 响应对象的状态码
print("\n状态码:", response.status_code)

4.编写爬虫程序

实例学习

Python爬虫教程-05-python爬虫实现百度翻译_python爬虫百度翻译 - CSDN博客
Python爬虫史上超详细讲解(零基础入门,老年人都看的懂)- CSDN博客

参考

[1] Python爬虫教程(从入门到精通)- C语言中文网
[2] Python 爬虫介绍 | 菜鸟教程
[3] Python urllib | 菜鸟教程
[4] Requests: 让 HTTP 服务人类 — Requests 2.18.1 文档
[5] Python requests 模块 | 菜鸟教程
[6] Python Requests库安装和使用 - C语言中文网
[7] Python re模块用法详解 - C语言中文网
[8] Python 正则表达式 | 菜鸟教程
[9] Beautiful Soup 中文文档
[10] Python BS4解析库用法详解 - C语言中文网


爬虫
http://example.com/2023/12/09/Python-爬虫/
许可协议