【问题标题】:Python finding exact string in .html filePython在.html文件中查找确切的字符串
【发布时间】:2017-01-30 13:29:53
【问题描述】:

我有一个 .html 文件,它会根据程序中执行的操作动态填充,但是在搜索确切的字符串时遇到问题,问题是虽然我知道该文件不是空白的,但循环不返回任何内容并认为它是空白的。

我已经搜索并阅读了许多其他 SO 问题并尝试了其中的许多问题,包括 'blah' in linere.findallwith open(),它们一直只返回空白,我想我需要 HTML 解析或类似的东西吗? 谁能帮我解释一下?

f = open(outApp + '_report.html', 'r+')
for line in f:
   #check the for loop works
   self.progressBox.AppendText(line)
   if 'mystring' in line:
       #do stuff

我希望找到的字符串是My country,它包含在 h2 标签中

【问题讨论】:

  • r+,你为什么写r+
  • 因为如果找不到'mystring',我想写入文件
  • 那么 afaik 应该是 r+w 或类似的东西。
  • 我正在继续我在这里找到的内容:pythonforbeginners.com/files/…‘r+’ – Special read and write mode, which is used to handle both actions when working with a file
  • @WillemVanOnsem r+ 对于打开文件读/写而不截断(文本模式)是正确的。 r+w 不是有效模式。

标签: python file parsing


【解决方案1】:

如果没有特殊的 HTML 解析器,绝对不应该这样做。

Google 关于任何你想要的 Python HTML 解析器。对于基本用法,它们都很容易。例如lxml。在伪代码中,您的任务是:

from some_cool_lib import SomeCoolHTMLParser
parser = SomeCoolHTMLParser()
doc = parser.parse(path_to_my_html_file)
h2_elements = doc.findall('h2')
for h2 in h2_elements:
   if h2.text == 'My country':
      # do stuff

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-09
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多