Python urllib2 模块

urllib2 可以用来打开各种协议的URL,基础用法如下:

In [1]: import urllib2
In [2]: request = urllib2.urlopen('http://www.baidu.com/')    # urlopen()用于打开一个URL,结果返回一个文件对象
In [3]: data = request.read()        # 使用文件对象的read()方法可以读取数据,也可以readline()、readlines()等方法


也可以通过构造一个请求对象,然后使用 urlopen() 来打开这个请求对象:

In [1]: import urllib2
In [2]: url = 'http://www.baidu.com/'
In [3]: ua = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36'In [4]: request = urllib2.Request(url, headers={'User-Agent': ua})    # headers用于指定请求头,User-Agent表示模拟哪个浏览器进行请求
In [5]: response = urllib2.urlopen(request)
In [6]: data = response.read()

    

猜你喜欢

转载自www.cnblogs.com/pzk7788/p/10372346.html
今日推荐