Python网络爬虫之——认识urllib库

不说废话,耿直,直接上案例。

案例1:百度首页爬取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#  导包
from urllib import request
# 确定爬取资源
base_url = 'http://www.baidu.com'
# 构建请求 发送请求
response = request.urlopen(base_url)
# 接受响应信息
html = response.read().decode('utf-8')
print(html) # 返回的是html源代码
# 信息存储
with open('./baidu.html','w',encodeing='utf-8') as f:
f.wirte(html)
```

### 案例2:get请求中url带中文字符

实现百度搜索。url地址会将url中的中文字符进行编码,所以当我们使用urllib发送此类url请求前要讲中文字符进行编码。

from urllib import request, parse # 1.导包
base_url = ‘http://www.baidu.com/s?' # 2.确定爬取资源
inp = input(‘输入搜索内容:’)
msg = { # 3.构造请求参数
‘wd’: inp
}
encodemsg = parse.urlencode(msg)
newurl = base_url+encodemsg # 将编码后的参数进行拼接
response = request.urlopen(newurl) #4. 构建请求 发送请求
html = response.read().decode(‘utf-8’) # 5.接受响应信息
print(html) # 返回的是html源代码
with open(‘./baidu.html’, ‘w’, encodeing=’utf-8’) as f: # 信息存储
f.wirte(html)

1
2
3
4

### 案例3:带user-agent反爬的网站

带有user-agent反爬的网站在发送请求之前必须要构建自己的请求头。

from urllib import request # 1.导包
base_url = ‘http://www.xicidaili.com' # 2.确定爬取资源
headers = { # 3.构造请求头与请求
‘User-Agent’: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36’
}
req = request.Request(url=base_url, headers=headers)
html = request.urlopen(req) # 4.发送请求
with open(‘./xici.html’,’w’,encodeing=’utf-8’) as f: # 5.接受并存储信息
f.write(html)

1
2
3
4

### 案例4:以上都是get请求 接下来做百度翻译(post请求)

先通过抓包工具F12 newwork分析,找到翻译时发送的请求,因为是异步请求又是post请求,所以还要找到传递的参数。直接上代码:

from urllib import request,parse
import ssl,json
ssl._create_default_https_context = ssl._create_unverified_context

确定爬取地址

base_url = ‘https://fanyi.baidu.com/sug'
def fanyi(msg):
dataform = { # 构造数据
‘kw’: msg
}
newdataform = parse.urlencode(dataform)
response = request.urlopen(url=base_url, data=bytes(newdataform, encoding=’utf-8’)) # 发送请求
res = response.read().decode(‘utf-8’) # 接受返回的数据
newres = json.loads(res)

# print(json.loads(res), type(json.loads(res)))
str = ''
for item in newres['data']:
    str += item['v'] + '\n'
print(str)

print(json.dumps(newres, indent=4, ensure_ascii=False)) # 将字典类型转换成字符串

if name == “main“:
while True:
msg = input(‘请输入要翻译的单词:’)
if msg == ‘q’: # 按q退出
break
fanyi(msg)

1
2

注意:如果发送请求时出现如下错误:

urllib.error.URLError:

1
这是因为ssl 验证的错误,可以将下面代码粘贴,解决不进行验证:

ssl._create_default_https_context = ssl._create_unverified_context
`

练习:爬取百度贴吧,根据用户输入的贴吧名称,页码范围来爬取指定贴吧指定页数范围。
爬取豆瓣电影的数据,这个是豆瓣电影的api:https://movie.douban.com/typerank?type_name=%E5%89%A7%E6%83%85&type=11&interval_id=100:90&action=