2 回答

TA贡献1946条经验 获得超4个赞
要使用库进行解析-最好的方法是BeautifulSoup, 以下是它对您的工作方式的一小段内容!
from BeautifulSoup import BeautifulSoup
src = "<html><body>...<div id=content>AAA<B>BBB</B>CCC</div>...</body></html>"
soupy = BeautifulSoup( src )
content_divs = soupy.findAll( attrs={'id':'content'} )
if len(content_divs) > 0:
# print the first one
print str(content_divs[0])
# to print the text contents
print content_divs[0].text
# or to print all the raw html
for each in content_divs:
print each

TA贡献1770条经验 获得超3个赞
是的,我已经做到了。这样做可能不是最好的方法,但是它的工作原理类似于下面的代码。我没有测试
import re
match = re.finditer("<div id=content>",src)
src = src[match.start():]
#at this point the string start with your div everything proceeding it has been stripped.
#This next part works because the first div in the string is the end of your div section.
match = re.finditer("</div>",src)
src = src[:match.end()]
src现在在字符串中仅包含div您的after。如果在某些情况下您想要的内容还有另一个,您只需要为您的重新查找部分建立一个更高级的搜索模式即可。
添加回答
举报