Python爬虫二:HTTP请求urllib与requests

一:urllib模块

urllib是Python中内置的发送网络请求的一个库(包),在Python2中由urllib和urllib2两个库来实现请求的发送,但是在Python3中已经不存在urllib2这个库了,已经将urllib和urllib2合并为urllib。
urllib 是标准库,它一个工具包模块,包含下面的模块处理 url:

urllib.request 用于打开和读写url
urllib.error 包含了有urllib.request引起的异常。
urllib.parse 用于解析url
urllib.robotparser 分析robots.txt 文件

1.1 urlopen()

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None) 

url参数,可以是一个string,或者一个Request对象。
data一定是bytes对象,传递给服务器的数据,或者为None。
目前只有HTTP requests会使用data,提供data时会是一个post请求,如若没有data,那就是get请求。data在使用前需要使用urllib.parse.urlencode()函数转换成流数据。

from urllib.request import urlopen
url = 'https://www.bing.com'
response = urlopen(url, timeout = 5)
print(response.closed)
with response:
    print(type(response))           # from http.client import HTTPResponse
    print(response.status, response.reason)
    print(response._method)
    print(response.read())          # 返回网页内容
    print(response.info())          # 获取响应头信息
    print(response.geturl())        # 请求的真正url(有的url会被301,302重定向)
	print(response.closed)

通过urllib.requset.urlopen 方法,发起一个HTTP的GET请求,web 服务器返回了网页内容,响应的数据被封装到类文件对象中,可以通过read方法,readline方法,readlines方法,获取数据,status,和reason 表示状态码, info方法表示返回header信息等

1.2 User-Agent

urlopen方法通过url 字符串和data发起HTTP请求,如果想修改HTTP头,例如:useragent 就得借助其他方式
urllib.request源码中构造的默认的useragent 如下:

# from urllib.request import OpenerDirector
class OpenerDirector:
    def __init__(self):
        client_version = "Python-urllib/%s" % __version__
        self.addheaders = [('User-agent', client_version)]

自定义构造请求头:

from urllib.request import urlopen, Request
url = 'https://www.bing.com'
user_agent = {
   "User-Agent": "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50"}
req = Request(url, headers = user_agent)    # 也可以通过下面行的代码添加user_agent到请求头
# req.add_header('User-Agent', user_agent)
response = urlopen(req, timeout = 5)	# url参数为一个Request对象
print(response.closed)
with response:
    print(type(response))           # from http.client import HTTPResponse
    print(response.status, response.reason)
    print(response._method)
    print(response.read())          # 返回网页内容
    print(response.info())          # 获取响应头信息
    print(response.geturl())        # 请求的真正url(有的url会被301,302重定向)
print(response.closed)

1.3 Request类

Request(url, data=None, headers={
   }# 初始化方法,构造一个请求对象,可添加一个header的字典
# data 参数决定是GET 还是POST 请求(data 为None是GET,有数据,就是POST)
# add_header(key, val) 为header中增加一个键值对。
import random
from urllib.request import urlopen, Request
url = 'http://www.bing.com'
user_agent_list = [
    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
    "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)"
]
user_agent = random.choice(user_agent_list)		# 随机选择user_agent
request = Request(url)
request.add_header('User-Agent', user_agent)
response = urlopen(request, timeout = 20)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值