繁体   English   中英

尝试从网页 Python 和 BeautifulSoup 中获取编码

[英]Trying to get encoding from a webpage Python and BeautifulSoup

我试图从网页中检索字符集(这会一直改变)。 目前我使用 beautifulSoup 来解析页面,然后从标题中提取字符集。 这工作正常,直到我遇到一个网站.....

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

到目前为止,我的代码与其他页面一起工作的是:

    def get_encoding(soup):
        encod = soup.meta.get('charset')
        if encod == None:
            encod = soup.meta.get('content-type')
            if encod == None:
                encod = soup.meta.get('content')
    return encod

有没有人知道如何添加到此代码以从上述示例中检索字符集。 将它标记化并尝试以这种方式检索字符集是一个想法吗? 您将如何在不更改整个功能的情况下进行操作? 现在上面的代码正在返回“text/html; charset=utf-8”,这会导致 LookupError 因为这是一种未知的编码。

谢谢

我最终使用的最终代码:

    def get_encoding(soup):
        encod = soup.meta.get('charset')
        if encod == None:
            encod = soup.meta.get('content-type')
            if encod == None:
                content = soup.meta.get('content')
                match = re.search('charset=(.*)', content)
                if match:
                    encod = match.group(1)
                else:
                    dic_of_possible_encodings = chardet.detect(unicode(soup))
                    encod = dic_of_possible_encodings['encoding'] 
    return encod
import re
def get_encoding(soup):
    if soup and soup.meta:
        encod = soup.meta.get('charset')
        if encod == None:
            encod = soup.meta.get('content-type')
            if encod == None:
                content = soup.meta.get('content')
                match = re.search('charset=(.*)', content)
                if match:
                    encod = match.group(1)
                else:
                    raise ValueError('unable to find encoding')
    else:
        raise ValueError('unable to find encoding')
    return encod

在我的情况下, soup.meta只返回在汤中找到的第一个meta soup.meta 这是@Fruit 的答案扩展到在给定的html中的任何meta标记中查找charset

from bs4 import BeautifulSoup
import re

def get_encoding(soup):
    encoding = None
    if soup:
        for meta_tag in soup.find_all("meta"):
            encoding = meta_tag.get('charset')
            if encoding: break
            else:
                encoding = meta_tag.get('content-type')
                if encoding: break
                else:
                    content = meta_tag.get('content')
                    if content:
                        match = re.search('charset=(.*)', content)
                        if match:
                           encoding = match.group(1)
                           break
    if encoding:
        # cast to str if type(encoding) == bs4.element.ContentMetaAttributeValue
        return str(encoding).lower()

soup = BeautifulSoup(html)
print(get_encoding_from_meta(soup))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM