gpt4 book ai didi

python - 使用 Python - 从一些 html 中获取表格并显示它?

转载 作者:太空宇宙 更新时间:2023-11-03 18:28:24 25 4
gpt4 key购买 nike

这里有很多帮助,但其中一些超出了我的理解范围,因此希望通过提出我的问题并获得量身定制的答案,我会更好地理解。

到目前为止,我已经成功连接到一个网站,以用户身份进行身份验证,填写表格,然后下拉 html。 html 包含一个我想要的表格。我只想说这样的话:-

读取 html...当您读取表格开始标记时,继续读取表格结束标记,然后显示该内容,或者将其写入新的 html 文件并打开它,保留标记,以便为我格式化。

这是我到目前为止的代码。

# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
s.post(LOGINURL, data=login)
# print
r = s.get(LOGINURL)
print r.url

# An authorised request.
r = s.get(APURL)
print r.url
# etc...

s.post(APURL)
#
r = s.post(APURL, data=findaps)
r = s.get(APURL)
#print r.text




f = open("makethisfile.html", "w")

f.write('\n'.join(['<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'<html>',
' <head>',
' <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">',
' <title>THE TITLE</title>',
' <link rel="stylesheet" href="css/displayEventLists.css" type="text/css">',
r.text #this just does everything, i need to get the table.
])
)

f.close()

最佳答案

尽管最好正确解析文件,但快速而肮脏的方法使用正则表达式。

m = re.search("<table.*?>(.+)</table>", r.text, re.S)
if (m):
print m.group()
else:
print "Error: table not found"

作为解析为何更好的示例,编写的正则表达式将失败,并显示以下(相当人为的!)示例:

<!-- <table> -->
blah
blah
<table>
this is the actual
table
</table>

正如所写的,它将获取文件中的第一个表。但是您可以循环获取第二个等(或者如果可能的话,使正则表达式特定于您想要的表),所以这不是问题。

关于python - 使用 Python - 从一些 html 中获取表格并显示它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22789095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com