初学者用python写爬虫就这么简单


很多人害怕python复杂,还没入门就被吓倒了,今天我就要证明个大家看,python很简单。(高手们就别提底层了,留点入门的信心我们吧,我们就写个爬虫玩玩,玩玩而已。)使用python写一个入门级的非常简单的爬虫。


#第一种方法

import urllib2  #将urllib2库引用进来
response=urllib2.urlopen("http://www.xiaofamao.com") #调用库中的方法,将请求回应封装到response对象中
html=response.read() #调用response对象的read()方法,将回应字符串赋给hhtml变量
print html  #打印出来

#第二中方法

import  urllib2
req=urllib2.Request("http://www.xiaofamao.com")
response=urllib2.urlopen(req)
html = response.read()
print  html

一般情况下,上面的爬虫,如果大量爬行,会被限制访问,所以要伪装成浏览器进行访问   
这里用伪装成IE9.0进行访问


#要求请的url地址

import urllib2
url="http://www.xiaofamao.com"
#要伪装的浏览器user_agent头
user_agent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36;"
#创建字典,使请求的headers中的’User-Agent‘:对应user_agent字符串
headers={'User-Agent':user_agent}
#新建一个请求,将请求中的headers变换成自己定义的
req =urllib2.Request(url,headers=headers)
#请求服务器,得到回应
response=urllib2.urlopen(req)
#得到回应内容
the_page=response.read()
#打印结果
print  the_page

猜你喜欢

转载自blog.csdn.net/i_like_cpp/article/details/79980379