开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第6天,点击查看活动详情
【Python】Python爬虫相关知识点
curl详解
用法讲解
| 参数 | 说明 | 实例 |
|---|---|---|
| -A | 设置user-agent | curl -A 'Chrome' www.baidu.com |
| -X | 指定请求方式 | curl -X POST www.baidu.com |
| -I | 返回请求头信息 | |
| -d | 以post方法请求url,并发送相应参数 | |
| 下载文件并以远程的文件名保存 | ||
| 可以自己命名保存文件 | ||
| -L | 跟随重定向请求 | |
| -H | 设置头信息 | |
| -k | 运行发起不安全的SSL请求 | |
| -b | 设置cookies | |
| 不显示其他无关信息 |
请求方法
| 方法 | 描述 |
|---|---|
| GET | 请求页面,并返回页面内容 |
| HEAD | 返回请求头 |
| POST | 用于提交表单或上传文件 |
| PUT | 从客户端向服务器传送的数据取代指定文档中的内容 |
| DELETE | 删除指定页面 |
| CONNECT | 把服务器当做跳板,让服务器代替客户端访问其他网页 |
| OPTIONS | 允许客户端查看服务器的性能 |
| TRACE | 主要用于测试或诊断 |
Requests库详解
Requests是用Python语言编写,基于urllib,采用Apache2 Licensed开源协议的HTTP库。它比urllib更加方便,可以节约我们大量的工作,满足HTTP测试需求。
基本用法
# requests库爬虫标准
import requests
url = 'http://www.baidu.com'
headers = {
'User-Agent':'Mozilla/5.0'
}
try:
response = requests.get(url, headers = headers)
response.raise_for_status()
response.encoding = r.apparent_encoding
return response.text
except:
print('爬取失败')
# 实例引入
import requests
response = requests.get('https://www.baidu.com/')
print(type(response))
print(response.status_code)
print(type(response.text))
print(response.text)
print(response.cookies)
# 各种请求方式
import requests
requests.post('http://httpbin.org/post')
requests.put('http://httpbin.org/put')
requests.delete('http://httpbin.org/delete')
requests.head('http://httpbin.org/get')
requests.options('http://httpbin.org/get')
# 带参数的get请求
import requests
data = {
'name':'gemey',
'age':22
}
response = requests.get('http://httpbin.org/get', params=data)
print(response.text)
# 转换成json格式
import requests
import json
response = requests.get('https://httpbin.org/get')
print(type(response.text))
print(response.json())
print(json.loads(response.text))
print(type(response.json()))
# 获取二进制数据
import requests
response = requests.get('http://github.com/favicon.ico')
with open('favicon.ico','wb') as f:
f.write(response.content)
f.close()
# 添加headers
import requests
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}
response = requests.get('https://www.zhihu.com/explore', headers=headers)
print(response.text)