如何在关键字后打印所有内容?例如打印单词“Apple”和单词“Pen”之间的所有内容

时间:2012-02-25 18:30:23

标签: python html

我需要创建一个脚本,显示关键字之间的所有字符。

让我们说,我下载html页面,然后阅读它(它有33985个字符)。我需要在"<td class="ml_subject"><a href="?tab=inbox""</a></td>"之间打印所有内容,这些内容是十几封信。

我可以通过以下方式找到起点:

if "<td class="ml_subject"><a href="?tab=inbox" in html:
    print "Success"

但那是什么?

5 个答案:

答案 0 :(得分:5)

使用find()方法: - &GT; http://docs.python.org/library/stdtypes.html#str.find

这看起来像这样:

# html is your input string
start = html.find( '<td class="ml_subject"><a href="?tab=inbox>' )
end = html.find( '</a></td>', start )
result = html[start:end]

答案 1 :(得分:3)

string = 'how to print everything after keyword ? for instance print everything between word “Apple” and word “Pen”'
s, e = string.index('Apple') + 5, string.index('Pen')
# plus 5 because we do not want to capture apple
print string[s:e]

答案 2 :(得分:2)

使用lxml或其他一些HTML处理模块:

from lxml.html import fragment_fromstring
from lxml.cssselect import CSSSelector

HTML = '<td class="ml_subject"><a href="?tab=inbox">Foobar</a></td>'

tree = fragment_fromstring(HTML)
selector = CSSSelector('td.ml_subject > a[href="?tab=inbox"]')
result = selector(tree)[0].text

答案 3 :(得分:0)

使用find查找字符串中的关键字,并使用切片表示法提取文本。如果找不到字符串,find将返回-1,请确保在实际实现中检查它。

>>> a = "stuff Apple more stuff Pen blah blah"
>>> delim1 = 'Apple'
>>> delim2 = 'Pen'
>>> i1 = a.find(delim1)
>>> i1
6
>>> i2 = a.find(delim2)
>>> i2
23
>>> a[i1+len(delim1):i2]
' more stuff '

答案 4 :(得分:0)

要打印所有链接文字,您可以使用BeautifulSoup

try:
    from urllib2 import urlopen
except ImportError: # Python 3.x
    from urllib.request import urlopen

from bs4 import BeautifulSoup # pip install beautifulsoup4

soup = BeautifulSoup(urlopen(url))
print('\n'.join(soup('a', href="?tab=inbox", text=True)))

如果链接必须有td.ml_subject个父级,那么您可以使用函数作为搜索条件:

def link_inside_td(tag):
    td = tag.parent
    return (tag.name == 'a' and tag.get('href') == "?tab=inbox" and
            td.name == 'td' and td.get('class') == "ml_subject")

print('\n'.join(soup(link_inside_td, text=True)))
相关问题