python爬虫是什么概述_python网络爬虫概述

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解析(待更新)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值