我想提取包含 IP blocks from this site 的表.
查看 HTML 源代码,我可以清楚地看到我想要的区域的结构如下:
[CONTENT BEFORE TABLE]
<table border="1" cellpadding="6" bordercolor="#000000">
[IP ADDRESSES AND OTHER INFO]
</table>
[CONTENT AFTER TABLE]
所以我写了这个小片段:
import urllib2,re
from lxml import html
response = urllib2.urlopen('http://www.nirsoft.net/countryip/za.html')
content = response.read()
print re.match(r"(.*)<table border=\"1\" cellpadding=\"6\" bordercolor=\"#000000\">(.*)</table>(.*)",content)
页面内容的获取(并且正确)没有问题。然而,正则表达式匹配始终返回 None
(此处的打印仅用于调试)。
考虑到页面的结构,我无法理解为什么没有匹配。我希望有三组,第二组是表格内容。
最佳答案
默认情况下,.
不匹配换行符。您需要指定dot-all flag让它这样做:
re.match(..., content, re.DOTALL)
下面是一个演示:
>>> import re
>>> content = '''
... [CONTENT BEFORE TABLE]
... <table border="1" cellpadding="6" bordercolor="#000000">
... [IP ADDRESSES AND OTHER INFO]
... </table>
... [CONTENT AFTER TABLE]
... '''
>>> pat = r"(.*)<table border=\"1\" cellpadding=\"6\" bordercolor=\"#000000\">(.*)</table>(.*)"
>>> re.match(pat, content, re.DOTALL)
<_sre.SRE_Match object at 0x02520520>
>>> re.match(pat, content, re.DOTALL).group(2)
'\n[IP ADDRESSES AND OTHER INFO]\n'
>>>
也可以通过使用 re.S
或将 (?s)
放在模式的开头来激活 dot-all 标志。
关于python - 使用正则表达式从网页中提取表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26821622/