美文网首页爬虫程序员
爬虫基础之urllib的简单使用 - get 请求(一)

爬虫基础之urllib的简单使用 - get 请求(一)

作者: 小飞牛_666 | 来源:发表于2018-04-24 16:36 被阅读68次
    爬虫里面,我们不可避免的要用urllib中的urlopen()方法去请求或获取一个网页的内容,这里面的区别在于urlopen打开URL网址,url参数可以是一个字符串url或者是一个Request对象,返回的是http.client.HTTPResponse对象.http.client.HTTPResponse对象大概包括read()、readinto()、getheader()、getheaders()、fileno()、msg、version、status、reason、debuglevel和closed函数,其实一般而言使用read()函数后还需要decode()函数,这里一个巨大的优势就是:返回的网页内容实际上是没有被解码或的,在read()得到内容后通过指定decode()函数参数,可以使用对应的解码方式。
    接下来我们以爬取百度首页为例:

    引入库

    import urllib.request  
    

    方式一:使用url直接请求百度网址

    def use_get1(url):
        html = urllib.request.urlopen(url).read()#请求并读取
        data = html.decode("utf-8") #解码
        return data
    
    #调用
    url = "http://www.baidu.com"
    response = use_get1(url)
    print(response)
    
    #执行 python urlopenget-1.py  (在命令行中进入爬虫文件所在的目录)
    

    方式二:使用 Request 对象并设置请求头

    def user_get2(url):
        req = urllib.request.Request(url)
        #添加请求头
        req.add_header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) \
            AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36")
        html = urllib.request.urlopen(req).read()#读取
        #写入文件中
        with open("C:\\Users\\Administrator\\Desktop\\feiniu\\lcy.html", "wb") as f:
            f.write(html)
    
    
    #调用
    url = "http://www.baidu.com"
    user_get2(url)
    

    带有关键字查询的get请求

    def use_get_key(url, key):
        new_url = url + urllib.request.quote(key) #对关键字部分进行编码
        req = urllib.request.Request(new_url)
        #添加请求头
        req.add_header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) \
            AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36")
        html = urllib.request.urlopen(req).read()
        #写入文件
        with open("C:\\Users\\Administrator\\Desktop\\feiniu\\yin.html", "wb") as f:
            f.write(html)
    
    
    #调用
    url = "http://www.baidu.com/s?wd="
    key = "飞牛冲天"
    use_get_key(url, key)
    

    相关文章

      网友评论

        本文标题:爬虫基础之urllib的简单使用 - get 请求(一)

        本文链接:https://www.haomeiwen.com/subject/tqsjlftx.html