gpt4 book ai didi

python - 抓取外文网页标题后在终端获取解码结果

转载 作者:太空宇宙 更新时间:2023-11-04 05:58:54 24 4
gpt4 key购买 nike

在此处输入代码如果您运行下面的程序来抓取日文网页的标题,我会得到未解码的结果。你能帮我用正确的语言获得结果吗?

(我的终端设置为utf-8。)

# coding: UTF-8
import codecs
import sys
import urllib
import re

urls = ["http://docs.python.jp/2/howto/regex.html", "http://docs.python.jp/2/library/urllib.html", "http://docs.python.jp/2/library/re.html"]
i = 0
regex = "<title>(.+?)</title>"
pattern = re.compile(regex)

while i< len(urls):
htmlfile = urllib.urlopen(urls[i])
htmltext = htmlfile.read()
titles = re.findall(pattern, htmltext)

print titles
i +=1

如果我运行这个文件,我会得到这些:

['\xe6\xad\xa3\xe8\xa6\x8f\xe8\xa1\xa8\xe7\x8f\xbe HOWTO &mdash; Python 2.7ja1 documentation']
['20.5. urllib \xe2\x80\x94 URL \xe3\x81\xab\xe3\x82\x88\xe3\x82\x8b\xe4\xbb\xbb\xe6\x84\x8f\xe3\x81\xae\xe3\x83\xaa\xe3\x82\xbd\xe3\x83\xbc\xe3\x82\xb9\xe3\x81\xb8\xe3\x81\xae\xe3\x82\xa2\xe3\x82\xaf\xe3\x82\xbb\xe3\x82\xb9 &mdash; Python 2.7ja1 documentation']
['7.2. re \xe2\x80\x94 \xe6\xad\xa3\xe8\xa6\x8f\xe8\xa1\xa8\xe7\x8f\xbe\xe6\x93\x8d\xe4\xbd\x9c &mdash; Python 2.7ja1 documentation']

最佳答案

问题似乎是 re.findall 函数返回了一个列表。通过打印列表,您的编码丢失了。这是一个快速修复:

import codecs
import sys
import urllib
import re

urls = ["http://docs.python.jp/2/howto/regex.html", "http://docs.python.jp/2/library/urllib.html", "http://docs.python.jp/2/library/re.html"]
i = 0
regex = "<title>(.+?)</title>"
pattern = re.compile(regex)

while i< len(urls):
htmlfile = urllib.urlopen(urls[i])
htmltext = htmlfile.read()
titles = re.findall(pattern, htmltext)

print titles[0]
i +=1

我添加了标题[0]

结果是:

正規表現 HOWTO &mdash; Python 2.7ja1 documentation
20.5. urllib — URL による任意のリソースへのアクセス &mdash; Python 2.7ja1 documentation
7.2. re — 正規表現操作 &mdash; Python 2.7ja1 documentation

***Repl Closed***

关于python - 抓取外文网页标题后在终端获取解码结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26199577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com