Python 爬虫基础篇——urllib库的使用

爬虫常用的几种技巧

1.基本方法

#-*-coding:UTF-8-*-
from urllib import request
response=request.urlopen("http://www.baidu.com/") #此处应该使用http
#http获取数据时信息齐全,https获取数据的信息有缺失,在确定网络地址后,一般采用http
content=response.read().decode('utf-8')
print(content)

2.伪装成浏览器

#-*-coding:UTF-8-*-
from urllib import request
url='http://www.baidu.com'
headers={"User-agent":"'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'"} #此处也可以设置成手机浏览器,模拟手机用户来爬取页面。
response=request.Request(url,headers=headers)
response=request.urlopen(response)
content=response.read().decode('utf-8')
print(content)

3.使用代理IP

#-*-coding:UTF-8-*-
from urllib import request
httpproxy=request.ProxyHandler({'http':'103.249.100.152:80'})#代理无需账号
opener=request.build_opener(httpproxy)#创建一个打开器
request=request.Request('http://www.baidu.com/')
response=opener.open(request)
print(response.read())

3.使用cookie

1. 输出cookie

#-*-coding:UTF-8 -*-
#这里使用的是python2.7
import urllib2 
import cookielib
cookie=cookielib.CookieJar()
httpcookieprocessor=urllib2.HTTPCookieProcessor(cookie)
opener=urllib2.build_opener(httpcookieprocessor)
response=opener.open("http://www.baidu.com")
cookies=''
for data in cookie:
	cookies=cookies+data.name+'='+data.value+';\n'
print cookies	

2.save cookie

#-*-coding:UTF-8 -*-
#这里使用的是python2.7
import urllib2 
import cookielib
file_path='cookie.txt'
cookie=cookielib.LWPCookieJar(cookie.xt)
httpcookieprocessor=urllib2.HTTPCookieProcessor(cookie)
opener=urllib2.build_opener(httpcookieprocessor)
response=opener.open("http://www.baidu.com")
cookie.save(ignore_expires=True,ignore_discard=True)

3.引用cookie

import urllib2
import cookielib
filepath="cookie.txt"
cookie=cookielib.LWPCookieJar()
cookie.load("cookie.txt",ignore_discard=True,ignore_expires=True)
header=urllib2.HTTPCookieProcessor(cookie)
opener=urllib2.build_opener(header)
response=opener.open('http://www.baidu.com')
print response.read()

4.注意:

1.python3导入urllib模块命令:import urllib,python2.7导入urllib模块命令是:import urllib2.
2.urllib.request.urlopen(python3)=urllib2.urlope(python2.7)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值