【问题标题】:Get value of log file in python from variable从变量中获取python中日志文件的值
【发布时间】:2015-12-25 01:55:56
【问题描述】:

我在一个变量中获取页面的源代码。

<!DOCTYPE html><html><head><title>Intro</title></head><body><a href='/name=t1.304.log'>Test</a>.  </body></html>

我想从上面的行中提取t1.304.log。 我正在使用 print log_name.split(".log",1)[0] 但它正在获取我的第一部分。

【问题讨论】:

  • 您能否通过从行中提取所需的字符串来详细说明您的意思?你想提取任何看起来像“something.log”的字符串吗?
  • 是的,任何以 .log 结尾的字符串。它只会出现一次
  • “仅一次”是指只有第一个匹配的子字符串吗?还是要确保字符串只包含一个匹配项?

标签: python html html-parsing


【解决方案1】:

为什么不用HTML parser 解析HTML?

>>> from bs4 import BeautifulSoup
>>> data = "<!DOCTYPE html><html><head><title>Intro</title></head><body><a href='/name=t1.304.log'>Test</a>.  </body></html>"
>>> BeautifulSoup(data).a["href"].split("=")[-1]
't1.304.log'

【讨论】:

    【解决方案2】:

    如果您只想快速完成此操作,可以使用记录在 here 中的 split() 函数。

    log_name.split("'")[1].split("=")[1]
    

    但是要以可重用的方式进行,请查看beautifulsoup之类的工具

    编辑添加

    根据您的 cmets,您可以这样做:

    print(log_name.split(".log",1)[0].rsplit("=",1)[1] + ".log")
    

    【讨论】:

    • 那不是字符串,我是从源代码中取值
    • import urllib url = 'google.com" logfile = urllib.urlopen(url) logfile = logfile.read() logfile= logfile.split(".log",1)[0].rsplit ("=",1)[1] + ".log")
    【解决方案3】:
       import re
        st = " <!DOCTYPE html><html><head><title>Intro</title></head><body><a href='/name=t1.304.log'>Test</a>.  </body></html>"
    
        mo = re.search('(t\S*log)', st)
    
        print(mo.group())
    

    输出

    t1.304.log
    

    【讨论】:

      【解决方案4】:

      假设您的字符串变量是page_source,您可以使用正则表达式(使用re 模块):

      >>> import re
      >>> re.findall('.*=(.*.log)', page_source)
      ['t1.304.log']
      

      这将为您提供所有匹配的“*.log”子字符串的列表。

      但是,请注意,显然不建议使用正则表达式来解析 HTML - 请参阅 this discussion

      其实别这样,用alecxe's answer

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-17
        • 1970-01-01
        • 2019-08-02
        • 2012-04-29
        • 1970-01-01
        • 2015-02-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多