我正在编写一个简短的Python脚本,在phpbb论坛数据库中找到指向Photobucket中托管的图片的所有URL,并将它们传递给下载管理器(在我的案例中为Free Download Manager)以保存图像在本地计算机上,然后在另一台主机上移动它们(现在Photobucket开始要求每年订阅一次,将其服务器中托管的图片嵌入其他网站)。我已经设法使用带有外观的正则表达式搜索所有图片,当我使用正则表达式搜索支持在两个文本编辑器上测试我的正则表达式时,我找到了我想要的但是在我的脚本中它给了我麻烦。
import re
import os
main_path = input("Enter a path to the input file:")
with open(main_path, 'r', encoding="utf8") as file:
file_cont = file.read()
pattern = re.compile(r'(?!(<IMG src=""))http:\/\/i[0-9][0-9][0-9]\.photobucket\.com\/albums\/[^\/]*\/[^\/]*\/[^\/]*(?=("">))')
findings = pattern.findall(file_cont)
for finding in findings:
print(finding)
os.system("pause")
我尝试调试它删除下载部分并打印所有匹配项,我得到了一长列表(''
,'"">'
),而不是与此类似的网址:http://i774.photobucket.com/albums/myalbum/Emi998/mypicture.jpg
哪里我错了?
答案 0 :(得分:1)
你的正则表达式模式不好。
我不确定您尝试做什么,如果您需要解析HTML(因为BeautifulSoup),我建议您使用Regex can not really parse HTML而不是使用正则表达式。
但无论如何 - 使用正则表达式 - 这应该有效:
r'<IMG src=\"(https?:\/\/i[0-9]{3}\.photobucket\.com\/albums[^\"]+)\"[^>]+\/>'
https?:\/\/i[0-9]{3}\.photobucket\.com\/albums
用于过滤非photobucket图像,[^\"]+
更通用,只提取所有内容,直到属性的最后"
个字符。
示例:
<IMG src="http://i774.photobucket.com/albums/myalbum/Emi998/mypicture.jpg" foo="bar"/>
给予.group(1)
:
http://i774.photobucket.com/albums/myalbum/Emi998/mypicture.jpg
答案 1 :(得分:0)
我认为你的正则表达式的以下版本应该有效:
请注意,我使用\"
代替""
,
我将img src
替换为img.+src
以支持img alt="" src
而不是[^\/]*
我使用[^\/]+
来移除\\
的验证,
对于URL的最后一部分,我还检查是否出现"
,
然后在>
之后完全按照"
进行检查,而不是在"
后.*
检查可选的其他字符。
(?!(<img.+src=\"))http:\/\/i\d{3}\.photobucket\.com\/albums\/[^\/]+\/[^\/]+\/[^\/\"]+(?=\".*/>)
^^ ^^^
您可以使用\d\d\d
或[0-9]{3}
或\d{3}
代替[0-9][0-9][0-9]
,