【问题标题】:Encoding issues with Python and beautifoulsoupPython 和 beautifoulsoup 的编码问题
【发布时间】:2022-01-18 16:28:52
【问题描述】:

我要从亚马逊上抓取一些页面。我想存储一些产品的标题。但是我的编码有问题。

def get_information_products(href):
    url = 'https://www.amazon.fr' + href
    url = Request(url)
    ua = UserAgent()
    url.add_header('User-Agent', ua.random)
    
    with urlopen(url) as f:
        data = f.readlines()  
    
    page_soup = soup(str(data), 'html.parser', from_encoding='iso-8859-1')
    title_list = []
    
    try:
        title = page_soup.find("span", attrs={"id": 'productTitle'})
        print(title.get_text(strip=True))
        return title.get_text(strip=True)
    except:
        return ''

这是获取数据的一段代码。之后,我要将数据保存到 csv。但我总是有同样的问题。我的产品标题是这样的:

OVO Sthira - Lot de 2 Briques de Yoga en Li\xc3\xa8ge Premium - Ultra Fin - Bloc Yoga - Brique Yoga - Block Yoga - Accessoire de Yoga \xc3\xa9cologique

我不知道如何用正确的字符保存数据...

【问题讨论】:

    标签: python web-scraping beautifulsoup encoding


    【解决方案1】:

    您的页面标题似乎是 UTF8,您可以试试这个:

    str = title.get_text(strip=True)
    str.encode("windows-1252").decode('utf8')
    

    如果是纯字符串,可能需要额外的步骤:

    str.decode("utf-8").encode("windows-1252").decode("utf-8")
    

    【讨论】:

      【解决方案2】:

      您可以尝试使用unicodedata 模块

      import unicodedata
      
      unicodedata.normalize("NFKD",your_text)
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-21
        • 1970-01-01
        • 2018-02-18
        • 2014-07-16
        • 1970-01-01
        • 2011-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多