为了账号安全,请及时绑定邮箱和手机立即绑定

在 python 中使用 lxml 进行网页抓取后,我得到奇怪的字符而不是土耳其字符

在 python 中使用 lxml 进行网页抓取后,我得到奇怪的字符而不是土耳其字符

三国纷争 2023-08-22 17:02:32
我一直在尝试使用 lxml lib 从一些网站获取数据。和Python3。但在网络抓取过程之后,我得到了一些奇怪的字符而不是土耳其字符。奇怪的字符如下所示。土耳其残疾人运动援助和教育总局 (TESYEV)关于单科考试的公告2019-2020 伊利学院研究院但它们应该像下面给出的那样。土耳其残疾人运动援助和教育基金会 (TESYEV) 总局关于单科考试的公告我们的学生在 2019-2020 学年要做的程序我从不同的网站得到了每个句子。我不知道如何将它们转换为土耳其语文本。这是我的代码。import cssselectimport requestsfrom lxml import htmldef parse_html(url, selector):    page = requests.get(url)    tree = html.fromstring(page.content)    titles = tree.cssselect(selector)    for title in titles:        print(title.text_content().strip())版本蟒蛇= 3.7.4lxml = 4.5.2请求= 2.24.0css选择= 1.1.0
查看完整描述

1 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

回答

import cssselect

import requests

from lxml import html


def parse_html(url, selector):

    page = requests.get(url)


    content = str(page.content, 'utf-8')


    tree = html.fromstring(content)

    titles = tree.cssselect(selector)


    for title in titles:

        print(title.text_content().strip())

为什么

unicode 字符“ı”(U+0131)在 UTF-8 中编码为0xC4B1 。2 字节。


> echo -e '\u0131' | xxd -u

00000000: C4B1 0A                                  ...

page.content返回二进制响应内容

0xC4B1变为0xC4 (U+00C4 '?') 和0xB1 (U+00B1 '±')

并且U+00FC 'ü'(UTF-8 编码:0xC3BC)变为0xC3 (U+00C3 'à') 和0xBC (U+00BC '¼')


查看完整回答
反对 回复 2023-08-22
  • 1 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信