刮谷歌学者安全页

2024-04-20 11:31:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一根线:

url = 'http://scholar.google.pl/citations?view_op\x3dsearch_authors\x26hl\x3dpl\x26oe\x3dLatin2\x26mauthors\x3dlabel:security\x26after_author\x3drukAAOJ8__8J\x26astart\x3d10'

我想把它转换成:

converted_url = 'https://scholar.google.pl/citations?view_op=search_authors&hl=en&mauthors=label:security&after_author=rukAAOJ8__8J&astart=10'

我试过这个:

converted_url = url.decode('utf-8')

但是,会引发以下错误:

AttributeError: 'str' object has no attribute 'decode'

Tags: viewhttpurlgoogleauthorsauthorplsecurity
1条回答
网友
1楼 · 发布于 2024-04-20 11:31:25

decode用于将bytes转换为string。你的网址是string,而不是bytes。你知道吗

您可以使用encode将此string转换为bytes,然后使用decode转换为正确的string。你知道吗

(我使用前缀r来模拟有这个问题的文本-没有前缀的url不需要转换)

url = r'http://scholar.google.pl/citations?view_op\x3dsearch_authors\x26hl\x3dpl\x26oe\x3dLatin2\x26mauthors\x3dlabel:security\x26after_author\x3drukAAOJ8__8J\x26astart\x3d10'
print(url)

url = url.encode('utf-8').decode('unicode_escape')
print(url)

结果:

http://scholar.google.pl/citations?view_op\x3dsearch_authors\x26hl\x3dpl\x26oe\x3dLatin2\x26mauthors\x3dlabel:security\x26after_author\x3drukAAOJ8__8J\x26astart\x3d10

http://scholar.google.pl/citations?view_op=search_authors&hl=pl&oe=Latin2&mauthors=label:security&after_author=rukAAOJ8__8J&astart=10

顺便说一句:首先检查print(url)也许您有正确的url,但您使用了错误的方法来显示它。pythonshell不使用print()显示所有结果,使用print(repr())显示一些字符作为代码,以显示文本中使用的endcoding(utf-8、iso-8859-1、win-1250、latin-1等)

相关问题 更多 >