1,网络请求
urllib(python自带)urllib3(urllib升级版)Requests(第三方)
1.1.urllib
import urllib.request as http # 引入文件请求库 lesson1
# 打印百度的网页信息
response = http.urlopen("http://www.baidu.com")
print(response.read().decode("utf-8"))
#lesion2 模拟post请求
import urllib.request as http
import urllib.parse as urlparse
data = bytes(urlparse.urlencode({"word": "hello_world"}), encoding='utf-8') # 设置参数
response = http.urlopen('http://httpbin.org/post', data=data) # 发送网络请求
html = response.read().decode('utf-8')
print(html)
1.2 urllib3
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', 'http://httpbin.org/robots.txt')
print(r.status)
print(r.data.decode())
#lesion 4 urllib3 post请求
import urllib3
http = urllib3.PoolManager()
response = http.request('POST', 'http://httpbin.org/post', fields={"word": "hello_world"})
html = response.data.decode()
print(html)
1.3Requests
# lesion5 requests使用
import requests
response = requests.get('https://www.baidu.com')
print('text----', response.content.decode('utf-8'))
print('status----', response.status_code)
print('url----', response.url)
#lesion6 requests post使用
import requests
data = {"word": "hello_world"}
response = requests.post("http://httpbin.org/post",data=data)
# print(response.text)
print(response.content.decode())
2,请求headers处理
请求网络内容时,网站为了防止被爬,会在header信息中进行加密。这个时候我们需要设置请求头文件header,具体操作如下,以百度为例:
2.1,首先查看头信息,以mac系统的火狐浏览器为例:
在百度网站,右键-查看元素-网络-选择200的一条消息-查看user-Agent:信息
image.png
复制对应的信息,填写到代码处如下:
import requests
header = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0) Gecko/20100101 Firefox/70.0'}
response = requests.get('https://www.baidu.com/', headers=header)
print(response.text)
3,网络超时处理
# lesion7 网络超时捕获 异常处理
import requests
for a in range(0, 50):
try:
response = requests.get('https://www.baidu.com/', timeout=0.1)
print(response.status_code)
except Exception as e
4,代理服务
当您的ip被所爬网站服务器屏蔽的时候,需要进行设置代理服务器(此处代码为模拟,不会有实际效果)
import requests
proxy = {'http': '122.144.31.177:80', 'https': '122.144.31.177:8080'}
response = requests.get('https://www.baidu.com',proxies=proxy)
print(response.text)
5,html解析(待更新)
网友评论