【问题标题】:AttributeError: 'NoneType' object has no attribute 'groups' in RegexAttributeError:“NoneType”对象在正则表达式中没有属性“组”
【发布时间】:2019-06-09 02:41:46
【问题描述】:

我编写了一个正则表达式来从网页中抓取数据。但是我收到了提到的错误。我无法找到解决方案。 有人建议

try:
    code
except:
     Attribute error

原代码:

import urllib.request
import bs4
import re

url ='https://ipinfo.io/AS7018'
def url_to_soup(url):
    req = urllib.request.Request(url)
    opener = urllib.request.build_opener()
    html = opener.open(req)
    soup = bs4.BeautifulSoup(html, "html.parser")
    return soup


s = str(url_to_soup(url))
#print(s)
asn_code, name = re.search(r'<h3 class="font-semibold m-0 t-xs-24">(?P<ASN_CODE>AS\d+) (?P<NAME>[\w.\s]+)</h3>', s)\
        .groups() # Error code
print(asn_code)
""" This is where the error : From above code """
country = re.search(r'.*href="/countries.*">(?P<COUNTRY>.*)?</a>',s).group("COUNTRY")
print(country)
registry = re.search(r'Registry.*?pb-md-1">(?P<REGISTRY>.*?)</p>',s, re.S).group("REGISTRY").strip()
print(registry)
# flag re.S make the '.' special character match any character at all, including a newline;
ip = re.search(r'IP Addresses.*?pb-md-1">(?P<IP>.*?)</p>',s, re.S).group("IP").strip()
print(ip)

【问题讨论】:

    标签: python regex web-scraping beautifulsoup


    【解决方案1】:

    声明:

    re.search(r'&lt;h3 class="font-semibold m-0 t-xs-24"&gt;(?P&lt;ASN_CODE&gt;AS\d+) (?P&lt;NAME&gt;[\w.\s]+)&lt;/h3&gt;', s)

    正在返回None 字符串s 中未找到您要查找的模式。

    根据re.search的文档

    扫描字符串,寻找正则表达式模式产生匹配的第一个位置,并返回相应的 MatchObject 实例。如果字符串中没有位置与模式匹配,则返回 None;请注意,这与在字符串中的某个点找到零长度匹配不同。

    您必须重新设计您的正则表达式或调试您的代码,以便在使用上述模式时找出s 包含的内容。

    【讨论】:

      【解决方案2】:

      re.search 在找不到任何东西时返回NoneNone 不响应方法.groups()。在详细检查匹配之前检查是否存在匹配。

      match = re.search(r'<h3 class="font-semibold m-0 t-xs-24">(?P<ASN_CODE>AS\d+) (?P<NAME>[\w.\s]+)</h3>', s)
      if match:
          asn_code, name = match.groups()
      

      但是,既然您使用的是 Beautiful Soup,为什么要先进行字符串化,然后再进行正则表达式匹配?这就像买一包速溶汤,将粉末加入水中,煮沸,然后将其脱水成粉末。那为什么还要使用 BeautifulSoup?

      soup.select('h3.font-semibold.m-0.t-xs-24')[0].content
      

      会给你&lt;h3&gt;元素的内容;如果需要,然后在 that 上应用正则表达式。通过 HTML 文档进行正则表达式是 generally a bad idea

      编辑:究竟是什么给了你TypeError?这是一个典型的XY problem,您正在解决错误的问题。我验证了这个工作,没有TypeError(Python 3):

      ast_re = re.compile(r'(?P<ASN_CODE>AS\d+) (?P<NAME>[\w.\s]+)')
      soup = url_to_soup(url)
      ast_h3 = next(
          (m for m in (ast_re.match(h3.text) for h3 in soup.select('h3')) if m),
          None)
      if ast_h3:
          asn_code, name = asn_h3.groups()
      

      【讨论】:

      • 感谢您的解决方案。它部分有效,因为我猜想一些我无法修复的正则表达式问题。但是,让我尝试回答第二部分我为什么要字符串化 bs4,因为它给了我“TypeError:预期的字符串或类似字节的对象”错误。无论如何,您可以帮助匹配正则表达式。我相信当有 &amp 时,正则表达式会拒绝它。我正在努力克服。
      猜你喜欢
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 2015-04-07
      相关资源
      最近更新 更多