Python urllib2 响应

Python urllib2 response

好的,所以我目前正在向网站发送 post 请求,然后在 html 中输出响应,我不想 print 整个页面,只是一些 div 括号内的具体内容..

我要输出的内容示例

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

所以我只想在td括号内输出“example”,我该怎么做?

HTML解析器就是为此任务而设计的。您可以为其提供整个 HTML 个响应页面。然后它将调用方法(您将在子类中覆盖)用于标记的条目(然后您检查它以确保它是具有属性 "right" 的 td 标记),数据的另一个方法(它将是一个字符串 "example" 和结束标记的另一种方法(您可以使用它来停止对数据方法做任何事情。

我喜欢 HTML解析器。看看吧。

编辑以添加草图示例:

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

我假设您对 Python/programming 总体来说还很陌生。

我推荐 requests 而不是内置 urllib2,因为它更易于使用。

对于元素选择,我认为 beautifulsoup 是使用起来最简单的库之一。

两者都易于安装:

  1. pip install requests

  2. pip install beautifulsoup4

代码:

import requests 
from bs4 import BeautifulSoup
url = 'https://en.wikibooks.org/wiki/Unicode/List_of_useful_symbols'
r = requests.get(url)
soup = BeautifulSoup(r.text)
tds = soup.findAll("td") # you can extract tags like <div> as well
print(tds)
td_texts = [td.text for td in tds] # in case you are interested in the text only 

输出:

[<td style="vertical-align:top">§</td>, <td> 00A7 section</td>, <td style="vertical-align:top">¶</td>, <td> 00B6 paragraph</td>, <td style="vertical-align:top">·</td>,