爬虫小案例 GET & POST

本文介绍了一种使用Python实现的网页请求方法,该方法能够通过GET或POST方式发送请求,并处理HTTP响应。主要讨论了如何设置请求头、解析URL参数以及处理常见的HTTP错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

def urlrequsets(url, form = None,headers=None):
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36'
    if headers ==None:
        headers = {
            'User-Agent' : user_agent
        }
    html_byte = b''
    print(555)
    try:
        #
    # 判断
        if form:
            # POST
            #转str
            form_str = parse.urlencode(form)
            # 转bytes
            form_bytes = form_str.encode('utf-8')
            req = request.Request(url, data=form_bytes, headers=headers)
        else:
            # GET
            req = request.Request(url,  headers=headers)
        response = request.urlopen(req)
        # print(999)
        # print(response)
        html_byte = response.read().decode('utf-8')

    except HTTPError as h:
        print(h)
    except URLError as u:
        print(u)
    except:
        # print(22222)

    return html_byte
if __name__ == '__main__':
    url = 'http://fanyi.baidu.com'
    form = {
        'kw' :'你好'
    }
    # print(111)
    html_byte = urlrequsets(url)
    # html_byte = json.loads(html_byte)
    print(html_byte)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值