簡體   English   中英

Python正則表達式匹配OpenWindow.document.write([this])

[英]Python Regex to match OpenWindow.document.write( [this] )

我有一個網頁,其中包含document.write javascript命令。 這些命令的結構如下:

OpenWindow.document.write("text that I want")

我想使用正則表達式返回所有[我想要的文本]的列表或匹配對象。 有人可以幫我嗎?

到目前為止的示例代碼:

f = open("filename",'r')
allhtml = f.read()
results = re.findall(the_regex,allhtml)

for s in results:
    Do Stuff

您可以嘗試這樣的正則表達式:

OpenWindow\.document\.write\s*\(\s*"((?:[^"\\]+|\\.)*)"\s*\)

如果始終是簡單的雙引號字符串。

它可以與轉義符一起工作,並且可以匹配以下內容:

OpenWindow.document.write("foo(\"bar\") baz('')")

請注意,這並非萬無一失:JS注釋,引號,正則表達式和其他HTML可能會為您帶來無效的結果。

In [69]: s
Out[69]: 'OpenWindow.document.write("text that I want")'

In [70]: r=re.findall(r'"(.*)"',s)

In [71]: r
Out[71]: ['text that I want']

或執行類似以下操作:

for line in my_html:
    if "OpenWindow.document.write" in line:
        r=re.search(r'"(.*)"',s)
        print r.group()

那這個呢?

import re

html = '...... your html page .... '
textlist = re.findall(r'OpenWindow\.document\.write\(([^\)]*)\)', html)

print "".join(textlist)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM