python的爬取html网页错误
 import requests
import xml.etree.ElementTree as ET
from xml.parsers.expat import ParserCreate

class DefaultSaxHandler(object):
    def __init__(self, provinces):
        self.provinces = provinces


    def start_element(self, name, attrs):
        pass

    def end_element(self, name):
        pass


    def char_data(self, text):
        self.provinces.append((text))

def get_province_entry(url):

    content = requests.get(url).content.decode('gb2312')

    start = content.find('<table height="22" cellSpacing="0" cellPadding="0" width="710" border="0">')
    end = content.find('<tr align="middle">')
    content = content[start:end ].strip()
    print(content)
    provinces = []

    handler = DefaultSaxHandler(provinces)

    parser = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data

    parser.Parse(content)

    return provinces

provinces = get_province_entry('http://www.ip138.com/post/')
print(provinces)

我想问下为什么打印出空值,我觉得是这部分错了,但是说不出哪里错

  def char_data(self, text):
        self.provinces.append((text))

1个回答

因为源码中

<table height="22" cellSpacing="0" cellPadding="0" width="710" border="0">

下一行就是

 <tr align="middle">

,所以造成content是空值

qq_40805263
qq_40805263 出现了这样的错误ExpatError Traceback (most recent call last) <ipython-input-5-63f77b6e02e7> in <module>() 39 return provinces 40 ---> 41 provinces = get_province_entry('http://www.ip138.com/post/') 42 print(provinces) <ipython-input-5-63f77b6e02e7> in get_province_entry(url) 35 parser.CharacterDataHandler = handler.char_data 36 ---> 37 parser.Parse(content) 38 39 return provinces ExpatError: undefined entity: line 6, column 55
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐