好的,我现在向一个网站发送一个帖子请求,然后在html中输出一个响应,我不想print整个页面,只是一些div括号中的特定内容。
要输出的内容示例
<td align="right"> example </td>所以我只想输出td括号中的“示例”,我该如何做呢?
发布于 2017-08-11 05:39:49
我假设您一般对Python/编程非常陌生。
我推荐requests而不是内置在urllib2中,因为它更容易使用。
对于元素选择,我认为beautifulsoup是使用的最简单的库之一。
这两者都很容易安装:
pip install requestspip 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>, 发布于 2017-08-11 05:35:28
HTMLParser是针对此任务设计的。您可以将整个HTML响应页面提供给它。然后,它将调用方法(您将在子类中重写该方法)以输入标记(然后检查该方法以确保它是带有属性“right”的td标记)、数据的另一个方法(它将是一个字符串“示例”)和另一个用于结束标记的方法(您可以使用它来停止对数据方法进行任何操作)。
我爱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 += datahttps://stackoverflow.com/questions/45627501
复制相似问题