使用python做最简单的爬虫

使用python做最简单的爬虫

--之心

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



#第二中方法
import urllib2
req=urllib2.Request("http://ww.baidu.com")
response=urllib2.urlopen(req)
html = response.read()
print html

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


#要求请的url地址
import urllib2
url="http://www.baidu.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

posted on 2017-12-09 22:23  之心  阅读(3707)  评论(0编辑  收藏  举报

导航