Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中查找HTML文件中的第一个表_Python_Python 2.7_Html Parsing - Fatal编程技术网

在python中查找HTML文件中的第一个表

在python中查找HTML文件中的第一个表,python,python-2.7,html-parsing,Python,Python 2.7,Html Parsing,我试图在HTML文件中找到第一个表,并复制表 到字符串s f = open('page.html' , 'r') s = "" for line in f.readlines(): line = line.strip() if line.find('<table'): s += line if line.find('</table>'): break print s f=open('page.html','r') s=“” 对于f.readline

我试图在
HTML
文件中找到第一个
,并复制
到字符串
s

f = open('page.html' , 'r')
s = ""
for line in f.readlines():
  line = line.strip()
  if line.find('<table'):
    s += line
  if line.find('</table>'):
    break
print s
f=open('page.html','r')
s=“”
对于f.readlines()中的行:
line=line.strip()

如果line.find(“尝试使用maybe,请参见此SO问题:

如果您必须坚持使用标准库,那么很明显您需要第一个
和最后一个
之间的内容

为此,您需要一个堆栈。从一开始就读取文件。每当遇到
时,推它在堆栈上的位置,每当看到
时,从堆栈中弹出一个。这将确保
与其对应的
匹配

注意最后一个
-如果从堆栈中弹出使其为空,则必须关闭第一个
,因此存储此位置


现在您有了第一个
和最后一个
的位置,因此您可以将它们之间的所有内容复制到一个字符串中。

您可以使用
正则表达式进行此操作

import re
tbl_pat = re.compile(r'<table(.*?)>(.*)</table>')
f = open('page.html' , 'r')
for line in f.readlines():
    m = tbl_pat.match(line)
    if m:
        print m.group(2)
        break
重新导入
tbl_pat=re.compile(r'(.*))
f=open('page.html','r')
对于f.readlines()中的行:
m=tbl_零件匹配(线)
如果m:
打印m.group(2)
打破

BeautifulSoup
请:@sshashank124:我必须使用标准python库您的第一行。查找缺少一个>在@gurka之后,这不是一个bug,这是一个功能:)它是像
@VeilEclipse这样的标记所需要的解决方案对您有帮助吗?如果有,接受一个怎么样?如果不告诉也。它不会捕获像
这样的标签。我不是第一次得到它。谢谢你指出。