python爬虫之基本知识


一、请求-响应

在利用python语言实现爬虫时,主要用到了urllib和urllib2两个库。首先用一段代码说明如下:

1 import urllib
2 import urllib2
3 
4 url="http://www.baidu.com"
5 request=urllib2.Request(url)
6 response=urllib2.urlopen(request)
7 print response.read()

我们知道一个网页就是以html为骨架,js为肌肉,css为衣服所构成的。上述代码所实现的功能就是把百度网页的源码爬取到本地。

其中,url为要爬取的网页的网址;request发出请求,response是接受请求后给出的响应。最后用read()函数输出的就是百度网页的源码。

二、GET-POST

两者都是向网页传递数据,最重要的区别是GET方式是直接以链接形式访问,链接中包含了所有的参数,当然如果包含了密码的话是一种不安全的选择,不过你可以直观地看到自己提交了什么内容。

POST则不会在网址上显示所有的参数,不过如果你想直接查看提交了什么就不太方便了,大家可以酌情选择。

POST方式:

1 import urllib
2 import urllib2
3 values={'username':'2680559065@qq.com','Password':'XXXX'}
4 data=urllib.urlencode(values)
5 url='https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn'
6 request=urllib2.Request(url,data)
7 response=urllib2.urlopen(request)
8 print response.read()

GET方式:

import urllib
import urllib2
values={'username':'2680559065@qq.com','Password':'XXXX'}
data=urllib.urlencode(values)
url = "http://passport.csdn.net/account/login"
geturl = url + "?"+data
request=urllib2.Request(geturl)
response=urllib2.urlopen(request)
print response.read()

三、异常处理

处理异常时,用到了try-except语句。

1 import urllib2
2 
3 try:
4     response=urllib2.urlopen("http://www.xxx.com")
5 except urllib2.URLError,e:
6     print e.reason

通过上述的介绍及代码展示,我们已经初步认识了爬虫过程,希望对大家有所帮助。

爬取图片:


import urllib
import urllib.request
import re
import os
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

def gethtml(url):
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
    req = urllib.request.Request(url=url, headers=headers)
    page=urllib.request.urlopen(req)
    html=page.read()
    html=html.decode('utf-8')
    return html
    
def getImg(html):
    reg='<img src="(http.*?\.png)"'
    imgre=re.compile(reg)
    imglist=imgre.findall(html)
    return imglist
    
def make_dir(floder):
    path=os.getcwd()+'/'+floder
    if not os.path.isdir(path):
        os.makedirs(path)
    return path

def save_image(path,imglist):
    x=0
    for imgurl in imglist:
        print(imgurl)
        urllib.request.urlretrieve(imgurl,'{}/{}.png'.format(path,x))
        x=x+1
    
if __name__=='__main__':
    html=gethtml('https://blog.csdn.net/yql_617540298/article/details/81411995')
    imglist=getImg(html)
    path=make_dir('test')
    save_image(path,imglist)
 

posted @ 2018-03-04 19:57  2048的渣渣  阅读(315)  评论(0编辑  收藏  举报