我有用PHP编写的代码,我想将其转换为python代码
$title_regex = "/<title>(.+)<\/title>/i";
preg_match_all($title_regex, $string, $title, PREG_PATTERN_ORDER);
$url_title = $title[1];
/// fecth decription
$tags = get_meta_tags($url);
// fetch images
$image_regex = '/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex, $string, $img, PREG_PATTERN_ORDER);
$images_array = $img[1];
我试过这个..但它在图片部分给我错误
import re
out=Data #web site html page ..
title_regex = "/<title>(.+)<\/title>/i" #no need for this .. un used
m = re.search("<title>(.+)<\/title>", out)
print "title",m.group(1)
#for pics i have tried this but it give me error ..
pics = re.match(r"/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui", out)#the conversion is not correct
print "grop",pics.group(1)
我的完整代码
import re
import urllib
print "Start"
url="http://www.deviantart.com"
data=urllib.urlopen(url)
out=data.read()
print
title_regex = "/<title>(.+)<\/title>/i"
m = re.search("<title>(.+)<\/title>", out)
print "first",m
print "title=",m.group(1)
title_regex = "/<title>(.+)<\/title>/i"
pics = re.match(r"/<img[^>]*src=[\"|\'](.*)[\"|\']/Ui", out)
print "pics>>",pics.group(1)
我如何将php重新转换为&gt;&gt;“/] *'。'src = \”| \'[\“| \'] / Ui”到python re?
答案 0 :(得分:2)
正则表达式可能找不到任何东西。
试试这个: 也删除最后的/ Ui
import re
out=Data #web site html page ..
title_regex = "/<title>(.+)<\/title>/i" #no need for this .. un used
if m is not None: # NEW <----------------
m = re.search("<title>(.+)<\/title>", out)
print "title",m.group(1)
#for pics i have tried this but it give me error ..
pics = re.match(r"<img[^>]*src=[\"|\'](.*)[\"|\']", out)
if pics is not None: # NEW <----------------
print "grop",pics.group(1)
为你第二个问题试试这个
for filename in pics.groups():
print filename
答案 1 :(得分:0)
工作版..使用标签IMG src显示来自给定网站的所有图像&gt; 代码:
import re
import urllib
print "Start"
url="http://www.deviantart.com"
data=urllib.urlopen(url)
out=data.read()
print
title_regex = "/<title>(.+)<\/title>/i"
m = re.search("<title>(.+)<\/title>", out)
print "first",m
print "grop",m.group(1)
title_regex = "/<title>(.+)<\/title>/i"
pics = re.compile(r"<IMG[^>]*src=([^>]*[^/])")#Change IMG tag
allpics=pics.findall(out)
print "found",pics
for mypic in allpics:
print "< IMG src=",mypic
感谢所有