Skip to content

Commit 8be49fc

Browse files
committed
update code in python_spider
1 parent 54a1524 commit 8be49fc

File tree

2 files changed

+53
-40
lines changed

2 files changed

+53
-40
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
# LearnPython
22
以撸代码的形式学习Python
33

4+
============================================================
45
### python_base.py: 千行代码入门Python
56

67
### python_visual.py: 15张图入门Matplotlib
78

89
### python_spider.py: 一个很“水”的Python爬虫入门代码文件
10+
============================================================
11+
12+
### 您可以fork该项目,并在修改后提交Pull request

python_spider.py

Lines changed: 49 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -9,79 +9,88 @@
99
import urllib.request
1010
import http.cookiejar
1111

12+
# 首先定义下边可能需要的变量
13+
url = "https://www.baidu.com"
14+
headers = {"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"}
1215

13-
# 最简单的方式
14-
response = urllib.request.urlopen("http://www.baidu.com", timeout=10)
16+
# 最简单的网页抓取方式
17+
response = urllib.request.urlopen(url, timeout=10)
1518
html = response.read().decode("utf-8")
1619

1720

18-
# 使用Request类
19-
request = urllib.request.Request("http://www.baidu.com/")
21+
# 使用Request实例代替url
22+
request = urllib.request.Request(url, data=None, headers={})
2023
response = urllib.request.urlopen(request, timeout=10)
2124

2225

23-
# 发送数据,即在urlopen()或者Request()中添加data参数
24-
url = "http://localhost/login.php"
26+
# 发送数据,即在Request()中添加data参数
2527
data = urllib.parse.urlencode({"act": "login", "email": "[email protected]", "password": "123456"})
26-
request1 = urllib.request.Request(url, data) # POST方法
27-
request2 = urllib.request.Request(url + "?%s" % data) # GET方法
28+
request1 = urllib.request.Request(url, data=data) # POST方法
29+
request2 = urllib.request.Request(url+"?%s" % data) # GET方法
2830
response = urllib.request.urlopen(request, timeout=10)
2931

3032

31-
# 发送Header,即在urlopen()或者Request()中添加headers参数
32-
headers = {"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"}
33+
# 发送Header,即在Request()中添加headers参数
3334
request = urllib.request.Request(url, data=data, headers=headers) # 参数中添加header参数
34-
request.add_header("Referer", "http://www.baidu.com") # add_header函数,另一种添加header的方法
35+
request.add_header("Referer", "http://www.baidu.com") # 另一种添加header的方式,添加Referer是为了应对"反盗链"
3536
response = urllib.request.urlopen(request, timeout=10)
3637

3738

38-
# 对付"反盗链":所谓的反盗链设置,就是检查header里的referer站点是不是他自己。所以只需要像把headers的referer改成某个网站自己即可
39-
headers = {"Referer": "http://www.baidu.com/"}
40-
41-
42-
# 引发异常:urllib.error.HTTPError, urllib.error.URLError, 两者存在继承关系
39+
# 网页抓取引发异常:urllib.error.HTTPError, urllib.error.URLError, 两者存在继承关系
4340
try:
4441
urllib.request.urlopen(request, timeout=10)
4542
except urllib.error.HTTPError as e:
4643
print(e.code, e.reason)
44+
except urllib.error.URLError as e:
45+
print(e.errno, e.reason)
4746

4847

4948
# 使用代理,以防止IP被封或IP次数受限:
50-
proxy = urllib.request.ProxyHandler({"http": "111.123.76.12:8080"})
51-
52-
opener = urllib.request.build_opener(proxy) # 利用代理创建opener实例(OpenerDirector实例)
53-
response = opener.open("https://www.baidu.com/") # 直接利用opener实例打开url
49+
proxy_handler = urllib.request.ProxyHandler(proxies={"http": "111.123.76.12:8080"})
5450

55-
urllib.request.install_opener(opener) # 安装、设置全局的opener,然后利用urlopen打开url
56-
response = urllib.request.urlopen("https://www.baidu.com/")
51+
opener = urllib.request.build_opener(proxy_handler) # 利用代理创建opener实例
52+
response = opener.open(url) # 直接利用opener实例打开url
5753

58-
59-
# 抓取网页中的图片:同样适用于抓取网络上的文件。右击鼠标,找到图片属性中的地址,然后进行保存。
60-
url = "http://ww3.sinaimg.cn/large/7d742c99tw1ee7dac2766j204q04qmxq.jpg"
61-
response = urllib.request.urlopen(url, timeout=120)
62-
with open("test.jpg", "wb") as file_img:
63-
file_img.write(response.read())
54+
urllib.request.install_opener(opener) # 安装全局opener,然后利用urlopen打开url
55+
response = urllib.request.urlopen(url)
6456

6557

66-
# 使用cookie和cookiejar
58+
# 使用cookie和cookiejar,应对服务器检查
6759
cookie_jar = http.cookiejar.CookieJar()
68-
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar=cookie_jar))
69-
response = opener.open("https://www.baidu.com/")
70-
for cookie in cookie_jar:
71-
print(cookie)
60+
cookie_jar_handler = urllib.request.HTTPCookieProcessor(cookiejar=cookie_jar)
61+
opener = urllib.request.build_opener(cookie_jar_handler)
62+
response = opener.open(url)
7263

7364

74-
# 发送在浏览器中获取的cookie,两种方式:(1)直接放到headers里,(2)构建cookie,添加到cookiejar中
75-
headers = {"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)",
76-
"Cookie": "PHPSESSID=btqkg9amjrtoeev8coq0m78396; USERINFO=n6nxTHTY%2BJA39z6CpNB4eKN8f0KsYLjAQTwPe%2BhLHLruEbjaeh4ulhWAS5RysUM%2B; "}
65+
# 发送在浏览器中获取的cookie,两种方式:
66+
# (1)直接放到headers里
67+
headers = {
68+
"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)",
69+
"Cookie": "PHPSESSID=btqkg9amjrtoeev8coq0m78396; USERINFO=n6nxTHTY%2BJA39z6CpNB4eKN8f0KsYLjAQTwPe%2BhLHLruEbjaeh4ulhWAS5RysUM%2B; "
70+
}
7771
request = urllib.request.Request(url, headers=headers)
7872

79-
cookie = http.cookiejar.Cookie(name="xx", value="xx", domain="xx")
73+
# (2)构建cookie,添加到cookiejar中
74+
cookie = http.cookiejar.Cookie(name="xx", value="xx", domain="xx", ...)
8075
cookie_jar.set_cookie(cookie)
81-
response = opener.open("https://www.baidu.com/")
76+
response = opener.open(url)
8277

8378

8479
# 同时使用代理和cookiejar
85-
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar=cookie_jar))
86-
opener.add_handler(urllib.request.ProxyHandler(proxies={"http": "http://www.example.com:8888/"}))
80+
opener = urllib.request.build_opener(cookie_jar_handler)
81+
opener.add_handler(proxy_handler)
8782
response = opener.open("https://www.baidu.com/")
83+
84+
85+
# 抓取网页中的图片:同样适用于抓取网络上的文件。右击鼠标,找到图片属性中的地址,然后进行保存。
86+
response = urllib.request.urlopen("http://ww3.sinaimg.cn/large/7d742c99tw1ee7dac2766j204q04qmxq.jpg", timeout=120)
87+
with open("test.jpg", "wb") as file_img:
88+
file_img.write(response.read())
89+
90+
91+
# HTTP认证:即HTTP身份验证
92+
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() # 创建一个PasswordMgr
93+
password_mgr.add_password(realm=None, uri=url, user='username', passwd='password') # 添加用户名和密码
94+
handler = urllib.request.HTTPBasicAuthHandler(password_mgr) # 创建HTTPBasicAuthHandler
95+
opener = urllib.request.build_opener(handler) # 创建opner
96+
response = opener.open(url, timeout=10) # 获取数据

0 commit comments

Comments
 (0)