打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
基于Python3的网络爬虫

本文适合没有接触过python或爬虫的人,需要有一定的编程经验和网络基础。


爬虫简单来说就是按照一定的规则,自动的抓取网上信息的程序或者脚本。


Python有对网络的良好支持和很好的灵活性,还容易上手,经常被人拿来做爬虫做分析找乐子,下面是个简单使用入门。


Python2和3的差别挺大,建议新手直接从3开始,下面例子基于3.4。


1,无脑抓

fromurllib import request

response= request.urlopen('http://www.baidu.com/')

content= response.read().decode('utf-8')

print(content)

2,代理

// IP被封或有时间限制,可使用代理

proxy_support = request.ProxyHandler({'http':'http://1.2.3.4:port'})

opener= request.build_opener(proxy_support, request.HTTPHandler)

// 如果只是临时使用这个代理,下面这句不加,直接使用opener.open()

request.install_opener(opener)

content= request.urlopen('http://www.baidu.com/').read().decode('utf-8')

print(content)

3,需要登录

3.1 处理cookie

fromurllib import request

from http import cookiejar // new

cookie_support= request.HTTPCookieProcessor(cookiejar.CookieJar())

opener= request.build_opener(cookie_support, request.HTTPHandler)

request.install_opener(opener)

content= request.urlopen('http://www.baidu.com/').read().decode('utf-8')

print(content)

同时使用代理的话,改成这个样子

proxy_support = request.ProxyHandler({'http':'http://1.2.3.4:port'})

opener= request.build_opener(proxy_support, cookie_support, request.HTTPHandler)

3.2 表单处理

先用工具分析出自己发出的包包含了哪些数据,一般至少会有username,password,还有其他的也一并记住

然后构造一个postdatafrom urllib import parse

postdata= parse.urlencode({

'username':'XXXXX',

'password':'XXXXX'

})

生成请求:

req= request.Request(

url = 'http://xxxxxxxxxxxxxxx',

data = postdata

)

content= request.urlopen(req).read()

print(content)

如果是get请求:

fullurl= 'http://xxxxxxxxxxxxxxx/index?%s'% data

req = request.Request(fullurl)

4,伪装用户

某些网站进制无名爬虫,所以要把自己伪装成正常人,简单来说就是改造一下请求的header

postdata= parse.urlencode({})

headers= {

'User-Agent':'Mozilla/5.0 (Windows; U;Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'

}

req= request.Request(

url = 'http://xxxxxxxxxxxxxxx',

data = postdata,

headers = headers

)

还有的网站喜欢检查请求的referer,看请求来源是否是本站,同样加个构造

headers= {

'Referer':'http://xxxxxxxxxxxxxxxxxxxxx'

}

大多数情况下单线程抓去会很慢,后面会在写点多线程和验证码的绕过方式


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
JustPy ? python 用urllib2抓取网页和发布(登录或发布文章)的基本操作
【Python必学】Python爬虫反爬策略你肯定不会吧?
Python 标准库 urllib2 的使用细节
零基础写python爬虫之urllib2使用指南
BATs朱学敏Python从0到1:用Cookie模拟登录金融系统
小白学 Python 爬虫(12):urllib 基础使用(二)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服