【发布时间】:2016-06-20 21:15:41
【问题描述】:
我正在尝试从 url 中提取元组,并且我已经成功地使用 re.search(pattern_str, text_str) 提取了 string text 和 tuples .但是,当我尝试使用 re.findall(pattern_str, text_str) 提取元组列表时,我遇到了困难。
文字如下:
<li>
<a href="11111">
some text 111
<span class="some-class">
#11111
</span>
</a>
</li><li>
<a href="22222">
some text 222
<span class="some-class">
#22222
</span>
</a>
</li><li>
<a href="33333">
some text 333
<span class="some-class">
#33333
</span>
</a>
... # repeating
...
...
我正在使用以下模式和代码来提取元组:
text_above = "..." # this is the text above
pat_str = '<a href="(\d+)">\n(.+)\n<span class'
pat = re.compile(pat_str)
# following line is supposed to return the numbers from the 2nd line
# and the string from the 3rd line for each repeating sequence
list_of_tuples = re.findall(pat, text_above)
for t in list_of tuples:
# supposed to print "11111 -> blah blah 111"
print(t[0], '->', t[1])
也许我正在尝试一些奇怪且不可能的事情,也许使用原始字符串操作提取数据会更好......但万一有解决方案?
【问题讨论】:
-
不要使用正则表达式解析 HTML。使用像美丽汤一样的解析器!