• python3 爬虫6--requests的使用(1)


    1用requests进行网页请求与urlopen差不多,这里省略不说

    2抓取网页的学习

    import requests

    import re

    headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}

    r=requests.get("https://www.zhuhu.com/explore",headers=headers)

    #下面是正则表达式,我在之后学习,这里我看不懂。。

    pattern = re.compile('explore-feed.*?question_link.*?>(.*?)</a>', re.S)

    titles = re.findall(pattern, r.text)

    print(titles)

    上面是知乎发现网页抓取的例子,唯一需要注意的是get请求的时候需要添加Headers,不能直接get请求。

    3抓取二进制数据

    r=requests.get('http://github.com/favicon.ico')

    print(r.text)

    print(r.content)

    抓取的目标是站点的图标

    r.text返回的是字符串类型,返回的结果是文本文件

    r.content如果返回的结果是图片、音频、视频文件,则获得字节流数据

    with open('favicon.ico','wb') as f:

      f.write(r.content)

    这样就可以把图标文件存储到了favicon.ico文件中,同样的音频、视频文件也能这样获取。

    4post请求

    post请求可以像表单提交一样,将表单数据添加到链接中

    data = {'name': 'germey', 'age': '22'}

    r = requests.post("http://httpbin.org/post", data=data)

    print(r.text)

    5respones

    我们可以通过get请求之后的respons获得更多的信息

    例如

    r=requests.get('http://www.jianshu.com')

    print(r.status_code)

    print(r.headers)

    print(r.cookies)

    print(r.url)

    我们可以判断查询码判断请求是否成功

    r = requests.get('http://www.jianshu.com')

    exit() if not r.status_code == requests.codes.ok else print('Request Successfully')

    print(r.history)

    状态码存储在Spider-python文件夹中。

  • 相关阅读:
    [GO]使用map生成 json
    [GO]通过结构体生成json
    [GO]正则表达式
    [GO]字符串的使用
    [GO]revoer的应用
    [GO]panic的应用
    微信公众平台自定义菜单及高级接口PHP SDK
    论MySQL何时使用索引,何时不使用索引
    MYSQL explain详解
    Mysql两种存储引擎的优缺点
  • 原文地址:https://www.cnblogs.com/daibigmonster/p/7528253.html
Copyright © 2020-2023  润新知