【发布时间】:2012-02-06 10:58:36
【问题描述】:
我正在登录一个站点,进行搜索查询,然后使用 beautifulsoup 过滤结果以获取“b”标签中的所有术语。从结果中我想检查搜索词(测试)是否存在。我当前的代码如下。我遇到的问题是,即使有结果并且存在该术语,我仍然得到一个不存在的响应。我已经打印了过滤后的查询并通读了它,结果肯定在那里,所以错误在搜索部分。我认为问题在于,在 html 中,testing 这个词本身并不是它的 Testing.example 或 Testing.test,因此搜索无法通过它自身被空格包围来找到它。如何在较长的单词/短语中搜索单词/短语。
我需要在“example.Testing.example”或“test.Testing.example”中找到“Testing”
希望这是有道理的。
谢谢
words = ["Testing"]
br.open ('http://www.example.com/browse.php?psec=2&search=%s' % words)
html = br.response().read()
soup = BeautifulSoup(html)
filtered = soup.findAll('b')
# print filtered
for word in words:
if word in filtered:
print "%s found." % word
else:
print "%s not found." % word
编辑
[<b><a title="Unknown">---</a></b>, <b>Welcome Back<br /><a href="/user/"><
span style="color:#0080FF;"></span></a>!<br /></b>, <b><span class="smallfo
nt"><a href="/messages.php?action=viewmailbox"><img height="14px" style="border:
none" alt="inbox" title="inbox (no new messages)" src="/pic/pn_inbox.gif" /></a>
59 (0 New)</span></b>, <b><span class="smallfont"> <a href="/message
s.php?action=viewmailbox&box=-1"><img height="14px" style="border:none" alt=
"sentbox" title="sentbox" src="/pic/pn_sentbox.gif" /></a> 37</span></b>, <b>Sho
w all</b>, <b><< Prev</b>, <b>Next >></b>, <b>1 - 7</b>, **<b>The.Testing
.example.T3Z6.L</b>**, <b><span style="color:#FF5500;">dgHn</span
></b>, <b><a href="/details.php?id=15829&hit=1&filelist=1">1</a></b>, <b
><a href="/details.php?id=15829&hit=1&=1"><font>30</font></a></
b>, <b><a href="/details.php?id=15829&hit=1&todlers=1">1</a></b>,
当我打印过滤后,我得到了上述结果。它稍长,但你明白了。从 **s 底部开始的五行,您会看到应该是正数但不是正数的结果。
【问题讨论】:
-
当你打印出
filtered的值是什么?能够添加print语句(或函数)以显示中间结果非常重要。 -
@S.Lott 我编辑了我的问题并添加到打印结果中。
标签: python beautifulsoup