Python爬虫

image-20221118194011249

测试数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="content-type" />
<meta content="IE=Edge" http-equiv="X-UA-Compatible" />
<meta content="always" name="referrer" />
<link href="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css" />
<title>百度一下,你就知道 </title>
</head>
<body link="#0000cc">
<div id="wrapper">
<div id="head">
<div class="head_wrapper">
<div id="u1">
<a class="mnav" href="http://news.baidu.com" name="tj_trnews"><!--注释新闻--></a>
<a class="mnav" href="http://news.baidu.com" name="tj_trnews">新闻</a>
<a class="mnav" href="https://www.hao123.com" name="tj_trhao123">hao123</a>
<a class="mnav" href="http://map.baidu.com" name="tj_trmap">地图</a>
<a class="mnav" href="http://v.baidu.com" name="tj_trvideo">视频</a>
<a class="mnav" href="http://tieba.baidu.com" name="tj_trtieba">贴吧</a>
<a class="bri" href="//www.baidu.com/more/" name="tj_briicon" style="display: block;">更多产品 </a>
</div>
</div>
</div>
</div>
</body>
</html>

urllib模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project :spider
@File :testUrllib.py
@Author :txy
@Date :2022/11/16 18:24
'''

import urllib.request

# 获取一个get请求
# response = urllib.request.urlopen("http://www.baidu.com")
# print(response.read().decode("utf-8")) # 使用utf-8将二进制编码解码

import urllib.parse
# 获取post请求
# data = bytes(urllib.parse.urlencode({"hellow":"word"}), encoding="utf-8")
# response = urllib.request.urlopen("https://httpbin.org/post", data=data) # https://httpbin.org接口测试网站
# print(response.read().decode("utf-8"))


# response = urllib.request.urlopen("https://httpbin.org/get", timeout=0.01) # 超时时退出本程序
# print(response.read().decode('utf-8'))

# response = urllib.request.urlopen("https://www.zhihu.com/")
# print(response.getheaders())


url = 'https://movie.douban.com/top250?start=0'
headers ={
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
}
data = bytes(urllib.parse.urlencode({'name':'eric'}), encoding='utf-8')
req = urllib.request.Request(url=url, data=data, headers=headers, method="POST")
res = urllib.request.urlopen(req)
print(res.read().decode('utf-8'))

# url='https://movie.douban.com/top250?start=0'
# headers={
# 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
# }
# data = bytes(urllib.parse.urlencode({'name':'jay'}),encoding='utf-8')
# req = urllib.request.Request(url=url,data=data,headers=headers,method='POST')
# response = urllib.request.urlopen(req)
# print(response.read().decode('utf-8'))

bs4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project :spider
@File :testBs4.py
@Author :txy
@Date :2022/11/16 22:43
'''
import re

'''
BeautifulSoup4将复杂的HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4中:

- Tag
- NavigableString
- BeautifulSoup
- Comment
'''

from bs4 import BeautifulSoup
# Beautiful Soup是一个可以从HTML或XML文件中提取数据的Python库,简单来说,它能将HTML的标签文件解析成树形结构,
# 然后方便地获取到指定标签的对应属性。
# 通过Beautiful Soup库,我们可以将指定的class或id值作为参数,来直接获取到对应标签的相关数据,这样的处理方式简洁明了。

file = open('./baidu.html', 'rb')
text = file.read().decode('utf-8')
bs = BeautifulSoup(text, "html.parser") # 创建了BeautifulSoup对象; HTML 数据将传递给构造函数。 第二个选项指定解析器。

# 1.Tag 标签及其内容;拿到它所找到的第一个内容。
# print(bs.body)
# print(bs.a.string)
# print(type(bs))

# 2.NavigableString 标签里的内容(字符串形式)
# print(bs.a)
# <a class="mnav" href="http://news.baidu.com" name="tj_trnews"><!--注释新闻--></a>
# print(bs.a.attrs)
# {'class': ['mnav'], 'href': 'http://news.baidu.com', 'name': 'tj_trnews'}

# 3.BeautifulSoup 表示整个文档
# print((bs.body))


# 4.Comment 特殊的NavigableString,输出的内容不包括注释符号
# print(bs.text)
# print(bs.a.string)
# 注释新闻


#-----------------------------------------------------------------


# 文档的遍历

# print(bs.body.contents)
# print(bs.head.contents)
# print(bs.head.contents[1])

# for child in bs.recursiveChildGenerator(): # 遍历所有元素
# if child.name:
# print(child.name)

# for child in bs.body.children: # 子节点遍历
# if child.name:
# print(child.name)

# (1)find_all()
# t_list = bs.find_all("a") # 查询所有的a标签
# print(t_list)


# import re
# # 使用正则表达式搜索:使用search()方法来匹配内容,在字符串的任意位置匹配
# t_list = bs.find_all(re.compile("")) # 查询所有包含字符a的字符串,这里相当于把整个bs当做一个字符串。
# print(t_list)


# (2) kwargs 参数

def print_list(list):
for item in list:
print(item)
#
# t_list = bs.find_all(text=re.compile("\d+")) # 注意class_后面有一个下划线,根基id查找没有下划线
# print_list(t_list)

# (3)text参数
# t_list = bs.find_all(text=re.compile("\d")) #应用正则表达式来查找特定文本的内容(标签中的字符串)
# print_list(t_list)


# (4)limit参数
# t_list = bs.find_all("a", limit=2) # 限制查找到的个数
# print_list(t_list)

# css选择器 根据css中的选择器查找对应的信息
# t_list = bs.select("title")
# print_list(t_list)

# t_list = bs.select(".mnav") # 根据类名查找
# print_list(t_list)

# t_list = bs.select("#wrapper") # 根据ID查找
# print_list(t_list)

# t_list = bs.select("head > title") # 根据子标签查找
# print_list(t_list)

t_list = bs.select(".mnav ~ .bri") # 根据兄弟标签查找
print_list(t_list)



正则表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project :spider
@File :testRe.py
@Author :txy
@Date :2022/11/17 21:30
'''

import re
# 正则表达式“字符串模式(判断字符串是否符合一定的标准)

# pat = re.compile("\d+") # 把常用的 正则表达式 编译成 正则表达式 对象,方便后续调用及提高效率。
# m = pat.search("9090de90fe")
# print(m)

# 没有模式对象
# m = re.search("\w+","dwedwd12_") # 前面为匹配规则,后面为要匹配的字符串。
# print(m)

# m = re.findall("\w","dwedwd12_") # 前面为匹配规则,后面为要匹配的字符串。
# print(m)

# sub

# print(re.sub("[0-9]", "*", "123456deded")) # 将符合要求的字符换成第二个参数

# 建议在正则表达中,在被比较的字符串前面加上r,就不用担心转义字符的问题。

# print(re.findall("\w+",r"\n\rsfefef32"))

保存数据

image-20221118100602298

requests

image-20221118194414428

接收响应

image-20221118194600487

网页解析器 Beautiful Soup

image-20221118203325075

创建Beautiful Soup对象

image-20221118203449324

image-20221118203635448

image-20221118203721953

image-20221118215025552