从变量获取python中日志文件的值

从变量获取python中日志文件的值,python,html,html-parsing,Python,Html,Html Parsing,我在一个变量中获取page的源代码 <!DOCTYPE html><html><head><title>Intro</title></head><body><a href='/name=t1.304.log'>Test</a>. </body></html> Intro。 我想从上述行中提取t1.304.log。 我使用的是printlog\u name.sp

我在一个变量中获取page的源代码

<!DOCTYPE html><html><head><title>Intro</title></head><body><a href='/name=t1.304.log'>Test</a>.  </body></html>
Intro。
我想从上述行中提取
t1.304.log

我使用的是print
log\u name.split(“.log”,1)[0]
但它为我获取了第一个完整部分。

如果您只想快速完成,可以使用
split()
函数

然而,要以可重用的方式进行,请查看以下工具

编辑以添加

根据您的评论,您可以这样做:

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

假设字符串变量为
page\u source
,则可以使用正则表达式(使用
re
模块):

>>> import re
>>> re.findall('.*=(.*.log)', page_source)
['t1.304.log']
这将为您提供所有匹配的“*.log”子字符串的列表

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


事实上,如果不这样做,请使用。

为什么不使用

>>来自bs4导入组
>>>data=“Intro。”
>>>美化组(数据).a[“href”].split(“=”)[-1]
“t1.304.log”

您能否通过从行中提取所需字符串来详细说明您的意思?是否要提取任何看起来像“something.log”的字符串?是任何以.log结尾的字符串。它只会出现一次,你是说只有第一个匹配的子字符串吗?或者您想确保该字符串只包含一个匹配项吗?这不是字符串,我从源代码导入urllib url='“logfile=urllib.urlopen(url)logfile=logfile.read()logfile=logfile.split(“.log”,1)[0].rsplit(“=”,1)[1]+.log”)
   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
>>> import re
>>> re.findall('.*=(.*.log)', page_source)
['t1.304.log']
>>> 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'