Python urllib2响应

时间:2017-08-11 05:22:17

标签: python urllib2

好的,我正在向网站发送帖子请求,然后以html格式输出回复,我不想print整个页面,只是某些div括号中的特定内容..

我要输出的内容示例

<td align="right"> example </td>

所以我只想输出&#34;例子&#34;在td括号内,我该怎么做?

1 个答案:

答案 0 :(得分:1)

HTMLParser专为此任务而设计。您可以将其提供给整个HTML响应页面。然后,它将调用方法(您将在子类中覆盖)以获取标记的条目(然后检查以确保它是具有属性“right”的td标记),这是数据的另一种方法(将是字符串“example”和结束标记的另一种方法(可用于停止使用数据方法执行任何操作。

我喜欢HTMLParser。看看吧。

编辑添加草图示例:

class MyParser(HTMLParser):
# Looking for <td class="example">
#               data here
#             </td>

    def __init__(self):
        super(MyParser, self).__init__()
        self.in_td = False
        self.data = ''

    def handle_starttag(self, tag, attrs):
        if tag != 'td':
            return
        d = dict(attrs)
        if 'class' in d and d['class'] == 'example':
            self.in_td = True

    def handle_endtag(self, tag):
        if tag=='td' and self.in_td:
            self.in_td = False
            print("Found this data: {}".format(self.data))

    def handle_data(self, data):
        if self.in_td:
            self.data += data
相关问题