Python 我想获取带有土耳其字符的html源代码,因此我需要将此代码与字符集结合起来

Python 我想获取带有土耳其字符的html源代码,因此我需要将此代码与字符集结合起来,python,Python,我将在主代码中添加此代码: # -*- coding: utf-8 -*- # -*- coding: iso-8859-9 -*- import urllib2 import urllib from lxml.html import fromstring from lxml.html.clean import Cleaner from formatter import NullFormatter from urllib2 import URLError import cookielib im

我将在主代码中添加此代码:

# -*- coding: utf-8 -*-
# -*- coding: iso-8859-9 -*-

import urllib2
import urllib
from lxml.html import fromstring
from lxml.html.clean import Cleaner
from formatter import NullFormatter
from urllib2 import URLError
import cookielib
import urllib,time
import urlparse
import datetime
import new
from htmllib import HTMLParser
from lxml.html import fromstring
from lxml.html.clean import Cleaner
import urllib2
import sys,popen2,os
import urlparse

def tagclean(url,Data=None):

    html =  urllib2.urlopen(url).read()
    doc = fromstring(html)
    tags = ['h1','h2','h3','h4','h5','h6',
       'div', 'span', 
       'img', 'area', 'map']
    args = {'meta':False, 'safe_attrs_only':False, 'page_structure':False, 
       'scripts':True, 'style':True, 'links':True, 'remove_tags':tags}
    cleaner = Cleaner(**args)

    path = '/html/body'
    body = doc.xpath(path)[0]
    return cleaner.clean_html(body).text_content().encode('ascii', 'ignore')
好东西。encode('ascii','ignore')
将删除您的土耳其语字符和其他非ascii字符。不要那样做。由于您似乎正在使用
ISO-8859-9
,请尝试使用它对Unicode字符进行编码


您使用的是什么操作系统?

对不起,这没有任何意义。请提出一个清晰简洁的问题。是的,它很复杂,我编辑得不好,我想编辑主代码tagclean,当你保存土耳其字符页面时,它正在删除土耳其字符,不要打印土耳其字符…打印没有土耳其字符的网页源…“ş,ç”例如,请编辑问题,并添加您遇到的问题以及预期结果。如果您理解meI,请编辑问题。这就是问题所在。它起作用了john我想把主网站的url分开,并把源代码标记为Cleaned。你能把这段代码添加到url html源代码爬虫程序中吗。@germandenis:在“它起作用了john”之后我什么都不懂。我想拿www.google.com和谷歌的url为例,我想分别拿url的源代码,我想说我想要一个网站url+html源代码爬虫。这个tagclean代码将与url爬行器相结合。
DEFAULT_ENCODING = 'utf-8'

def parse_content_type(response):
    try:
        ctype = response.info()['Content-Type']
    except KeyError:
        raise URLError('No Content-Type defined.')
    try:
        ctype, encoding = ctype.split(';')
        # encoding is now "charset=enc"
            _, encoding = encoding.split('=')
    except ValueError:
        # no or wrong encoding definition, use default
        encoding = DEFAULT_ENCODING
        try:
            ctype = ctype.split(';')[0]
        except IndexError:
            raise URLError('Could not parse Content-Type: "%s"' % ctype)

    return ctype, encoding

//This function should return "text/html" as Content-Type.

ctype, encoding = parse_content_type(response)

if not ctype == 'text/html':
    raise URLError('Wrong Content-Type: "%s"' % ctype)