Python数据分析___爬虫入门—2

Python数据分析___爬虫入门—2

1 爬虫入门:

1.1 练习urllib库:

第一,这里是基于Python3,而不是基于Python2的,两者有区别;

第二,在Python中,很多库可以用来抓取网页,urllib是其中之一。

第三,练习使用urllib(库).request(模块)的urlopen(函数)

from urllib.request import urlopen

response=urlopen("https://www.hao123.com")

print(response.read())

注:

​ 建议使用Fiddler抓包工具,来展现:请求、响应的过程;

​ 如果启动了Fiddler抓包工具,地址要写:https://www.hao123.com;

​ 如果没有启动,地址写:http://www.hao123.com;

上述python代码的执行结果为:

b'<!DOCTYPE html><html><head><noscript><meta http-equiv="refresh" content="0; URL=\'/?
...
省略很多很多行
...

1.2 修改User-Agent:

第一,在Filddler中,双击选中左侧:www.hao123.com,在右侧部分,请求部分的Raw,显示:User-Agent: Python-urllib/3.6

第二,由上集知道:User-Agent (浏览器名称),标识客户端身份的名称,通常页面会根据不同的客户端身份,自动做出适配,甚至返回不同的响应内容。

第三,因此,需要修改User-Agent,以免Web服务器认为我们不是浏览器,进行拦截

from urllib.request import urlopen,Request

a=Request("http://www.hao123.com")		#生成Request类的实例对象,初始化需要传入url

a.add_header("User-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36")
#这一步修改了请求报头,将我们的Pycharm访问,伪装成Google浏览器访问

response=urlopen(a)

with response:	    				#上下文管理器,主要是为了打开文件内容后,自动关闭
    print("response.read())

注:函数urlopen()可以传入Request类;
	Request类的初始化需要传入url,Request类的实例具备add_header方法,添加请求报头信息;

1.3 查看Response:

查看一下返回的response的属性:状态码、url等等

from urllib.request import urlopen,Request
from http.client import HTTPResponse
url="http://www.bing.com"

a=Request(url)
a.add_header("User-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36")
response=urlopen(a)

print(response.closed)		#打印出False

with response:
    print(type(response))	#打印出: 
    print(response._method)	#GET
    print(response.status)	#打印出:200
    print(response.reason)	#打印出:OK
    print(response.geturl())#打印出:http://cn.bing.com/
    print(response.info())	#打印出info: Cache-Control: private, max-age=0,等等
    print(response.read())	#b'
                    
                    

你可能感兴趣的:(Python数据分析___爬虫入门—2)