Skip to content

Commit 402e056

Browse files
committed
更新了文档
1 parent 822ffd0 commit 402e056

16 files changed

+229
-28
lines changed

Day41-55/Django2实战02.md

+49-27
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,9 @@ Type "help", "copyright", "credits" or "license" for more information.
342342
>>>
343343
>>> Dept.objects.filter(no__gt=10).filter(no__lt=40) # 查询部门编号大于10小于40的部门
344344
<QuerySet [<Dept: 销售1部>, <Dept: 运维1部>]>
345+
>>>
346+
>>> Dept.objects.filter(no__range=(10, 30)) # 查询部门编号在10到30之间的部门
347+
<QuerySet [<Dept: 研发1部>, <Dept: 销售1部>, <Dept: 运维1部>]>
345348
```
346349

347350
查询单个对象。
@@ -350,8 +353,10 @@ Type "help", "copyright", "credits" or "license" for more information.
350353
>>>
351354
>>> Dept.objects.get(pk=10)
352355
<Dept: 研发1部>
356+
>>>
353357
>>> Dept.objects.get(no=20)
354358
<Dept: 销售1部>
359+
>>>
355360
>>> Dept.objects.get(no__exact=30)
356361
<Dept: 运维1部>
357362
```
@@ -362,6 +367,7 @@ Type "help", "copyright", "credits" or "license" for more information.
362367
>>>
363368
>>> Dept.objects.order_by('no') # 查询所有部门按部门编号升序排列
364369
<QuerySet [<Dept: 研发1部>, <Dept: 销售1部>, <Dept: 运维1部>, <Dept: 研发3部>]>
370+
>>>
365371
>>> Dept.objects.order_by('-no') # 查询所有部门按部门编号降序排列
366372
<QuerySet [<Dept: 研发3部>, <Dept: 运维1部>, <Dept: 销售1部>, <Dept: 研发1部>]>
367373
```
@@ -372,6 +378,7 @@ Type "help", "copyright", "credits" or "license" for more information.
372378
>>>
373379
>>> Dept.objects.order_by('no')[0:2] # 按部门编号排序查询1~2部门
374380
<QuerySet [<Dept: 研发1部>, <Dept: 销售1部>]>
381+
>>>
375382
>>> Dept.objects.order_by('no')[2:4] # 按部门编号排序查询3~4部门
376383
<QuerySet [<Dept: 运维1部>, <Dept: 研发3部>]>
377384
```
@@ -382,37 +389,43 @@ Type "help", "copyright", "credits" or "license" for more information.
382389
>>>
383390
>>> Emp.objects.filter(dept__no=10) # 根据部门编号查询该部门的员工
384391
<QuerySet [<Emp: 乔峰>, <Emp: 张无忌>, <Emp: 张三丰>]>
392+
>>>
385393
>>> Emp.objects.filter(dept__name__contains='销售') # 查询名字包含“销售”的部门的员工
386394
<QuerySet [<Emp: 黄蓉>]>
395+
>>>
387396
>>> Dept.objects.get(pk=10).emp_set.all() # 通过部门反查部门所有的员工
388397
<QuerySet [<Emp: 乔峰>, <Emp: 张无忌>, <Emp: 张三丰>]>
389398
```
390399

391-
> 说明:由于员工与部门之间存在外键关联,所以也能通过部门反向查询该部门的员工(从一对多关系中“一”的一方查询“多”的一方),默认情况下反查属性名是`类名小写_set`(例子中的`emp_set`),当然也可以在创建模型时通过`related_name`指定反查属性的名字。
400+
> 说明1:由于员工与部门之间存在多对一外键关联,所以也能通过部门反向查询该部门的员工(从一对多关系中“一”的一方查询“多”的一方),反向查询属性默认的名字是`类名小写_set`(如上面例子中的`emp_set`),当然也可以在创建模型时通过`ForeingKey``related_name`属性指定反向查询属性的名字。如果不希望执行反向查询可以将`related_name`属性设置为`'+'`或以`'+'`开头的字符串。
401+
402+
> 说明2:查询多个对象的时候返回的是QuerySet对象,QuerySet使用了惰性查询,即在创建QuerySet对象的过程中不涉及任何数据库活动,等真正用到对象时(求值QuerySet)才向数据库发送SQL语句并获取对应的结果,这一点在实际开发中需要引起注意!
403+
404+
> 说明3:可以在QuerySet上使用`update()`方法一次更新多个对象。
392405
393406
#### 删除
394407

395408
```Shell
396-
409+
>>>
410+
>>> Dept.objects.get(pk=40).delete()
411+
(1, {'hrs.Dept': 1})
397412
```
398413

399-
最后,我们通过上面掌握的知识来实现部门展示以及根据部门获取部门对应员工信息的功能,效果如下图所示,对应的代码可以访问<>。
400-
401414
### Django模型最佳实践
402415

403416
1. 正确的模型命名和关系字段命名。
404-
2. 设置适当的related_name属性
405-
3. 用OneToOneField代替ForeignKeyField(unique=True)。
406-
4. 通过迁移操作来添加模型
417+
2. 设置适当的`related_name`属性
418+
3. `OneToOneField`代替`ForeignKeyField(unique=True)`
419+
4. 通过“迁移操作”(migrate)来添加模型
407420
5. 用NoSQL来应对需要降低范式级别的场景。
408-
6. 如果布尔类型可以为空要使用NullBooleanField
421+
6. 如果布尔类型可以为空要使用`NullBooleanField`
409422
7. 在模型中放置业务逻辑。
410-
8. 用ModelName.DoesNotExists取代ObjectDoesNotExists
423+
8. `<ModelName>.DoesNotExists`取代`ObjectDoesNotExists`
411424
9. 在数据库中不要出现无效数据。
412-
10. 不要对QuerySet调用len函数
413-
11. 将QuerySet的exists()方法的返回值用于if条件
414-
12. 用DecimalField来存储货币相关数据而不是FloatField
415-
13. 定义\_\_str\_\_方法
425+
10. 不要对`QuerySet`调用`len()`函数
426+
11. `QuerySet``exists()`方法的返回值用于`if`条件
427+
12. `DecimalField`来存储货币相关数据而不是`FloatField`
428+
13. 定义`__str__`方法
416429
14. 不要将数据文件放在同一个目录中。
417430

418431
> 说明:以上内容来自于STEELKIWI网站的[*Best Practice working with Django models in Python*](https://steelkiwi.com/blog/best-practices-working-django-models-python/),有兴趣的小伙伴可以阅读原文。
@@ -513,22 +526,31 @@ ManyToManyField属性
513526
| verbose_name | 为对象设定人类可读的名称 |
514527
| verbose_name_plural | 设定对象的复数名称 |
515528

516-
### 数据库API参考
529+
### 查询参考
517530

531+
按字段查找可以用的条件:
518532

533+
1. exact / iexact:精确匹配/忽略大小写的精确匹配查询
534+
2. contains / icontains / startswith / istartswith / endswith / iendswith:基于`like`的模糊查询
535+
3. in:集合运算
536+
4. gt / gte / lt / lte:大于/大于等于/小于/小于等于关系运算
537+
5. range:指定范围查询(SQL中的`between…and…`
538+
6. year / month / day / week_day / hour / minute / second:查询时间日期
539+
7. isnull:查询空值(True)或非空值(False)
540+
8. search:基于全文索引的全文检索
541+
9. regex / iregex:基于正则表达式的模糊匹配查询
542+
543+
Q对象(用于执行复杂查询)的使用:
544+
545+
```Shell
546+
>>>
547+
>>> from django.db.models import Q
548+
>>> Emp.objects.filter(
549+
... Q(name__startswith=''),
550+
... Q(sal__gte=5000) | Q(comm__gte=1000)
551+
... ) # 查询名字以“张”开头 工资大于等于5000或补贴大于等于1000的员工
552+
<QuerySet [<Emp: 张三丰>]>
553+
```
519554

520-
按字段查找可以用的条件:
521555

522-
1. exact / iexact
523-
2. contains / icontains
524-
3. in
525-
4. gt / gte / lt / lte
526-
5. startswith / istartswith / endswith / iendswith
527-
6. range
528-
7. year / month / day / week_day / hour / minute / second
529-
8. isnull
530-
9. search
531-
10. regex / iregex
532-
533-
跨关系查找
534556

File renamed without changes.
File renamed without changes.
File renamed without changes.

Day66-75/res/baidu-search-taobao.png

427 KB
Loading
233 KB
Loading

Day66-75/res/postman.png

329 KB
Loading

Day66-75/存储数据.md

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
## 存储数据
2+
3+
### 缓存和持久化
4+
5+
### 磁盘文件缓存
6+
7+
### 数据库缓存
8+

Day66-75/并发下载.md

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
## 并发下载
2+

Day66-75/数据清洗.md

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
## 数据清洗
2+

Day66-75/数据采集和解析.md

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
## 数据采集和解析
2+
3+
### HTML页面分析
4+
5+
### 三种采集方式
6+
7+
8+

Day66-75/爬虫中的陷阱.md

Whitespace-only changes.

Day66-75/缓存数据.md

Whitespace-only changes.
+159
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
## 网络爬虫和相关工具
2+
3+
### 网络爬虫
4+
5+
网络爬虫(web crawler),以前经常称之为网络蜘蛛(spider),是按照一定的规则自动浏览万维网并获取信息的机器人程序(或脚本),曾经被广泛的应用于互联网搜索引擎。使用过互联网和浏览器的人都知道,网页中除了供用户阅读的文字信息之外,还包含一些超链接。网络爬虫系统正是通过网页中的超链接信息不断获得网络上的其它页面。正因如此,网络数据采集的过程就像一个爬虫或者蜘蛛在网络上漫游,所以才被形象的称为网络爬虫或者网络蜘蛛。
6+
7+
#### 爬虫的应用领域
8+
9+
在理想的状态下,所有ICP(Internet Content Provider)都应该为自己的网站提供API接口来共享它们允许其他程序获取的数据,在这种情况下爬虫就不是必需品,国内比较有名的电商平台(如淘宝、京东等)、社交平台(如腾讯微博等)等网站都提供了自己的Open API,但是这类Open API通常会对可以抓取的数据以及抓取数据的频率进行限制。对于大多数的公司而言,及时的获取行业相关数据是企业生存的重要环节之一,然而大部分企业在行业数据方面的匮乏是其与生俱来的短板,合理的利用爬虫来获取数据并从中提取出有价值的信息是至关重要的。当然爬虫还有很多重要的应用领域,以下列举了其中的一部分:
10+
11+
1. 搜索引擎
12+
2. 新闻聚合
13+
3. 社交应用
14+
4. 舆情监控
15+
5. 行业数据
16+
17+
### 合法性和背景调研
18+
19+
#### 爬虫合法性探讨
20+
21+
1. 网络爬虫领域目前还属于拓荒阶段,虽然互联网世界已经通过自己的游戏规则建立起一定的道德规范(Robots协议,全称是“网络爬虫排除标准”),但法律部分还在建立和完善中,也就是说,现在这个领域暂时还是灰色地带。
22+
2. “法不禁止即为许可”,如果爬虫就像浏览器一样获取的是前端显示的数据(网页上的公开信息)而不是网站后台的私密敏感信息,就不太担心法律法规的约束,因为目前大数据产业链的发展速度远远超过了法律的完善程度。
23+
3. 在爬取网站的时候,需要限制自己的爬虫遵守Robots协议,同时控制网络爬虫程序的抓取数据的速度;在使用数据的时候,必须要尊重网站的知识产权(从Web 2.0时代开始,虽然Web上的数据很多都是由用户提供的,但是网站平台是投入了运营成本的,当用户在注册和发布内容时,平台通常就已经获得了对数据的所有权、使用权和分发权)。如果违反了这些规定,在打官司的时候败诉几率相当高。
24+
25+
#### Robots.txt文件
26+
27+
大多数网站都会定义robots.txt文件,下面以淘宝的[robots.txt](http://www.taobao.com/robots.txt)文件为例,看看该网站对爬虫有哪些限制。
28+
29+
```
30+
User-agent: Baiduspider
31+
Allow: /article
32+
Allow: /oshtml
33+
Disallow: /product/
34+
Disallow: /
35+
36+
User-Agent: Googlebot
37+
Allow: /article
38+
Allow: /oshtml
39+
Allow: /product
40+
Allow: /spu
41+
Allow: /dianpu
42+
Allow: /oversea
43+
Allow: /list
44+
Disallow: /
45+
46+
User-agent: Bingbot
47+
Allow: /article
48+
Allow: /oshtml
49+
Allow: /product
50+
Allow: /spu
51+
Allow: /dianpu
52+
Allow: /oversea
53+
Allow: /list
54+
Disallow: /
55+
56+
User-Agent: 360Spider
57+
Allow: /article
58+
Allow: /oshtml
59+
Disallow: /
60+
61+
User-Agent: Yisouspider
62+
Allow: /article
63+
Allow: /oshtml
64+
Disallow: /
65+
66+
User-Agent: Sogouspider
67+
Allow: /article
68+
Allow: /oshtml
69+
Allow: /product
70+
Disallow: /
71+
72+
User-Agent: Yahoo! Slurp
73+
Allow: /product
74+
Allow: /spu
75+
Allow: /dianpu
76+
Allow: /oversea
77+
Allow: /list
78+
Disallow: /
79+
80+
User-Agent: *
81+
Disallow: /
82+
```
83+
84+
注意上面robots.txt第一段的最后一行,通过设置“Disallow: /”禁止百度爬虫访问除了“Allow”规定页面外的其他所有页面。因此当你在百度搜索“淘宝”的时候,搜索结果下方会出现:“由于该网站的robots.txt文件存在限制指令(限制搜索引擎抓取),系统无法提供该页面的内容描述”。百度作为一个搜索引擎,至少在表面上遵守了淘宝网的robots.txt协议,所以用户不能从百度上搜索到淘宝内部的产品信息。
85+
86+
![](./res/baidu-search-taobao.png)
87+
88+
### 相关工具介绍
89+
90+
#### HTTP协议
91+
92+
93+
94+
#### 相关工具
95+
96+
1. Chrome Developer Tools
97+
98+
![](./res/chrome-developer-tools.png)
99+
100+
2. POSTMAN
101+
102+
![](./res/postman.png)
103+
104+
3. HTTPie
105+
106+
```Shell
107+
$ http --header http://www.scu.edu.cn
108+
HTTP/1.1 200 OK
109+
Accept-Ranges: bytes
110+
Cache-Control: private, max-age=600
111+
Connection: Keep-Alive
112+
Content-Encoding: gzip
113+
Content-Language: zh-CN
114+
Content-Length: 14403
115+
Content-Type: text/html
116+
Date: Sun, 27 May 2018 15:38:25 GMT
117+
ETag: "e6ec-56d3032d70a32-gzip"
118+
Expires: Sun, 27 May 2018 15:48:25 GMT
119+
Keep-Alive: timeout=5, max=100
120+
Last-Modified: Sun, 27 May 2018 13:44:22 GMT
121+
Server: VWebServer
122+
Vary: User-Agent,Accept-Encoding
123+
X-Frame-Options: SAMEORIGIN
124+
```
125+
126+
4. BuiltWith:识别网站使用的技术
127+
128+
```Python
129+
>>>
130+
>>> import builtwith
131+
>>> builtwith.parse('http://www.bootcss.com/')
132+
{'web-servers': ['Nginx'], 'font-scripts': ['Font Awesome'], 'javascript-frameworks': ['Lo-dash', 'Underscore.js', 'Vue.js', 'Zepto', 'jQuery'], 'web-frameworks': ['Twitter Bootstrap']}
133+
>>>
134+
>>> import ssl
135+
>>> ssl._create_default_https_context = ssl._create_unverified_context
136+
>>> builtwith.parse('https://www.jianshu.com/')
137+
{'web-servers': ['Tengine'], 'web-frameworks': ['Twitter Bootstrap', 'Ruby on Rails'], 'programming-languages': ['Ruby']}
138+
```
139+
140+
5. python-whois:查询网站的所有者
141+
142+
```Python
143+
>>>
144+
>>> import whois
145+
>>> whois.whois('baidu.com')
146+
{'domain_name': ['BAIDU.COM', 'baidu.com'], 'registrar': 'MarkMonitor, Inc.', 'whois_server': 'whois.markmonitor.com', 'referral_url': None, 'updated_date': [datetime.datetime(2017, 7, 28, 2, 36, 28), datetime.datetime(2017, 7, 27, 19, 36, 28)], 'creation_date': [datetime.datetime(1999, 10, 11, 11, 5, 17), datetime.datetime(1999, 10, 11, 4, 5, 17)], 'expiration_date': [datetime.datetime(2026, 10, 11, 11, 5, 17), datetime.datetime(2026, 10, 11, 0, 0)], 'name_servers': ['DNS.BAIDU.COM', 'NS2.BAIDU.COM', 'NS3.BAIDU.COM', 'NS4.BAIDU.COM', 'NS7.BAIDU.COM', 'dns.baidu.com', 'ns4.baidu.com', 'ns3.baidu.com', 'ns7.baidu.com', 'ns2.baidu.com'], 'status': ['clientDeleteProhibited https://icann.org/epp#clientDeleteProhibited', 'clientTransferProhibited https://icann.org/epp#clientTransferProhibited', 'clientUpdateProhibited https://icann.org/epp#clientUpdateProhibited', 'serverDeleteProhibited https://icann.org/epp#serverDeleteProhibited', 'serverTransferProhibited https://icann.org/epp#serverTransferProhibited', 'serverUpdateProhibited https://icann.org/epp#serverUpdateProhibited', 'clientUpdateProhibited (https://www.icann.org/epp#clientUpdateProhibited)', 'clientTransferProhibited (https://www.icann.org/epp#clientTransferProhibited)', 'clientDeleteProhibited (https://www.icann.org/epp#clientDeleteProhibited)', 'serverUpdateProhibited (https://www.icann.org/epp#serverUpdateProhibited)', 'serverTransferProhibited (https://www.icann.org/epp#serverTransferProhibited)', 'serverDeleteProhibited (https://www.icann.org/epp#serverDeleteProhibited)'], 'emails': ['[email protected]', '[email protected]'], 'dnssec': 'unsigned', 'name': None, 'org': 'Beijing Baidu Netcom Science Technology Co., Ltd.', 'address': None, 'city': None, 'state': 'Beijing', 'zipcode': None, 'country': 'CN'}
147+
```
148+
149+
6. robotparser:解析robots.txt的工具
150+
151+
### 一个简单的爬虫
152+
153+
构造一个爬虫一般分为数据采集、数据处理和数据存储三个部分的内容。
154+
155+
首先我们要设定抓取的目标并获取网页。
156+
157+
1. 设置重试次数。
158+
2. 设置用户代理。
159+

Day66-75/网络爬虫简介和相关工具.md

Whitespace-only changes.

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@
249249

250250
### Day66~75 - [爬虫](./Day66-75)
251251

252-
#### Day66 - [爬虫简介和相关工具](./Day66-75/爬虫简介和相关工具.md)
252+
#### Day66 - [网络爬虫和相关工具](./Day66-75/网络爬虫和相关工具.md)
253253

254254
#### Day67 - [数据采集和解析](./Day66-75/数据采集和解析.md)
255255

0 commit comments

Comments
 (0)