在除最后一个之外的所有正则表达式测试中获得“AttributeError”

时间:2018-04-05 06:57:29

标签: python regex

我的代码应该遍历文件的每一行并执行操作。该文件看起来像这样: FIREFOX::https://addons.mozilla.org/en-US/firefox/addon/ogame-fleet-counter/::<dd class=\"MetadataCard-content\">(.*?)<\/dd>

每行有3件事:名称 :: 网址 :: 正则表达式

代码运行良好,文件中有1行,但不止于此,代码只适用于最后一行,其他代码只是抛出错误:AttributeError: 'NoneType' object has no attribute 'group'

我尝试使用其他方法来运行该文件,因为我认为错误存在,但显然这不是问题。

#!/usr/bin/python
import re
import urllib2
import sys

with open("addons.cfg", "r") as addons:
    for line in addons:
        try:
            name, url, regex = line.split("::")
            response = urllib2.urlopen(url)
            page_source = response.read()

            m = re.search(regex, page_source)
            if m:
                print(m.group(1))
            else:
                print("Couldn't find!")
        except:
            print "Unexpected error:", sys.exc_info()[0]
            raise

视频以更好地显示错误:https://youtu.be/j_lwnlrj-fg

1 个答案:

答案 0 :(得分:0)

发现我的错误,我不得不使用regex.strip()

#!/usr/bin/python
import re
import urllib2
import sys

with open("addons.cfg", "r") as addons:
    for line in addons:
        name, url, regex = line.split("::")
        source = urllib2.urlopen(url).read()
        regex = regex.strip()
        try:
            regex_result = re.search(regex, source)
            if regex_result:
                print(regex_result.group(1))
            else:
                print("error")
        except:
            print "Unexpected error:", sys.exc_info()[0]
            raise