內的字符串我有一個HTML頁面內一些線路是這樣的:找到一個段落,找到這一段用正則表達式
<div>
<p class="match"> this sentence should match </p>
some text
<a class="a"> some text </a>
</div>
<div>
<p class="match"> this sentence shouldnt match</p>
some text
<a class ="b"> some text </a>
</div>
我想提取<p class="match">
裏面的線,但只有當裏面有div
含<a class="a">
。
什麼,我這樣做的遠低於(我首先找到<a class="a">
裏面的段落,我在迭代結果找到一個<p class="match">
裏面的句子):
import re
file_to_r = open("a")
regex_div = re.compile(r'<div>.+"a".+?</div>', re.DOTALL)
regex_match = re.compile(r'<p class="match">(.+)</p>')
for m in regex_div.findall(file_to_r.read()):
print(regex_match.findall(m))
,但我不知道是否有另一種(仍然有效)的方式一次做到這一點?
嘗試美麗湯4解析HTML文件.. – 2014-08-28 17:04:48
http://stackoverflow.com/a/1732454 – carloabelli 2014-08-28 17:04:54