Python判断网页编码

本文总结了在Python爬虫中遇到的网页编码问题及其解决方案,包括通过正则匹配、使用chardet库直接判断转换以及requests库的内置方法。提供了一种获取网页标题、内容和外链的类实现。
摘要由CSDN通过智能技术生成

title: Python判断网页编码
copyright: true
top: 0
date: 2018-05-04 17:37:58
tags: 基础
categories: 爬虫笔记
permalink:
password:
keywords: [Python爬虫,编码]
description: 做爬虫或者测试的时候,返回网页的编码是个很让人头疼的问题,这篇文章做个网页编码问题解决方法总结。

有一种渴,只有酒才能滋润,这种渴就是孤独。

根据网页返回编码寻找数据

比如我要找到这个网页的标题,那么直接正则匹配(.*?)就可以,但是许多时候因为编码问题requests这个库没办法正确解析,所以获取不到数据。

解决办法:

        r_port_top = requests.get(url=str('http://'+url), headers=headers, timeout=5)
        if r_port_top.encoding == 'ISO-8859-1':
            encodings = requests.utils.get_encodings_from_content(r_port_top.text)
            if encodings:
                encoding = encodings[0]
            else:
                encoding = r_port_top.apparent_encoding
            encode_content = r_port_top.content.decode(encoding, 'replace').encode('utf-8', 'replace')
            port_title = re.search('<title>(.*?)</title>', encode_content, re.S).group().replace('<title>',
                                                                                                 '').replace(
                '</title>', '')

这种办法就是先判断网页的编码,然后转换之。但是有的时候是utf-8编码就没办法,接下来来个终极版的。

    try:
        UA = random.choice(headerss)
        headers = {'User-Agent': UA}
        r_port_top = requests.get(url=str('http://'+url), headers=headers, timeout=5)
        if r_port_top.encoding == 'ISO-8859-1':
            encodings = requests.utils.get_encodings_from_content(r_port_top.text)
            if encodings:
                encoding = encodings[0]
            else:
                encoding = r_port_top.apparent_encoding
            encode_content = r_port_top.content.decode(encoding, 'replace').encode('utf-8', 'replace')
            port_title = re.search('<title>(.*?)</title>', encode_content, re.S).group().replace('<title>',
                                                                                                 '').replace(
                '</title>', '')
        e
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浪子燕青啦啦啦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值