python数据采集之requests

python数据采集之requests

利用requests库发起get或者post请求

使用代码范例

import requests
from lxml  import etree
from fake_useragent import UserAgent
import json
import time
#随机请求头
ua=UserAgent()

# get请求
def get_url(url):
    header={
        "User-Agent":ua.random
    }
    res=requests.get(url,headers=header)

    if res.status_code==200:
        html=etree.HTML(res.content)
        # 字段名以及xpath规则添加 可添加多个 返回的字段类型为list
        name=html.xpath("//div[@id='content']/h1/text()")

    else:
        print("error url:%s,状态码"%(url,res.status_code))

# post请求
def post_url(url):
    header = {
        "User-Agent": ua.random
    }
    payload={
        "key1":"value1",
        "key2": "value2",
        "key3": "value3",
        "key4": "value4",

    }
    #请求时视情况而定看是否需要带上数据表单
    # 数据表单的使用   data=json.dumps(payload)
    response=requests.post(url,headers=header)
    try:
        if response.status_code==200:
            #请求内容为转为json
            datas = json.loads(response.text)['data']["list"]
            for data in datas:
                title=data['title']
                print(title)
    except Exception as e:
        print(e)

if __name__ == '__main__':
    # url添加 这里以豆瓣top250为例
    geturl='https://movie.douban.com/top250'
    get_url(geturl)
    # csdns 区块链的api
    posturl = 'https://blockchain.csdn.net/m/zone/blockchain/blog_api?page=1'
    post_url(posturl)

使用前需要下载 requests、lxml、fake-useragent,json库

此范例可作为requests库爬取数据的一个模板,可根据自己的需求进行相应的扩充

requests中文文档: https://2.python-requests.org//zh_CN/latest/user/quickstart.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值