python - 使用正则表达式从网页中提取表格

标签 python html regex web-scraping html-table

我想提取包含 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/

相关文章:

python - 使用 sklearn columntransfromer 时解压错误

Python通过http发送数据和jpg

regex - 用斜线捕获模式后的单词

python - 将带括号的内容过滤到 Python 列表中

javascript - 正则表达式附加字符并删除结束双引号

python - 使用随机模型和随机变量对人口建模

python - 生成一个 mel 脚本

javascript - 在 Shadow DOM 中平滑滚动

html - 如何将 LaTeX Sweave 文件 (Rnw) 转换为 HTML?

html - html 中的图像未正确对齐