[英]Python regex: search for HTML tags and modify them
我有一個HTML文件作為字符串,並且想要將所有<img src="http:.../../filename.png ..>
更改為<img src="id:filename.png>
正則表達式?
到目前為止,我得到了:
urls = re.findall(r'src=[\'"]?([^\'" >]+)', html)
allUrls = ', '.join(urls)
如果您控制HTML,則可以使用正則表達式。
蟒蛇:
import re
html = re.sub(r'(<img src=").+/(.+">)', r'\1id:\2', html)
HTML:
<img src="http://example.com/filename1.jpg">
<img src="http://example.com/filename2.jpg">
否則,正則表達式將變得非常混亂。 我建議使用lxml 。 BeautifulSoup也很棒。
import lxml.etree, os, urlparse
root = lxml.etree.HTML(html)
for img in root.iter("img"):
src = img.get("src", None)
if src is not None:
if urlparse.urlparse(src).scheme in ("http", "https"):
src_path = urlparse.urlparse(src).path
src_path_base = os.path.basename(src)
src = "id:" + os.path.basename(src)
img.set("src", src)
html = lxml.etree.tostring(root)
這可以應付許多情況,如果使用正則表達式,即使不是不可能的情況,它們也會很尷尬。 例子:
<img src=http://example.com/filename.jpg>
<img src=http%3A%2F%2Fexample.com%2Ffilename.jpg>
<img title="src=http://example.com/bait.jpg" src=http://example.com/filename.jpg>
<img src=data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==>
<img
src
=
http://example.com/filename.jpg
>
<img src="http://example.com/book report cover.jpg"> <!-- invalid but common -->
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.