Skip to main content
 首页 » 编程设计

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

2025年05月04日12傻小

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

(我的终端设置为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***