【问题标题】:Byte error in regexp正则表达式中的字节错误
【发布时间】:2014-08-01 13:32:18
【问题描述】:

所以,这里是代码:

#!/usr/bin/python
from sys import exit
import urllib.request

answer = urllib.request.urlopen("http://monip.org").read()

def debug(txt):
    print(txt)
    exit(0)

def parse_answer(answer):
    ''' Simple function to parse request's HTML result
        to find the ip in it. Raise RuntimeError if no 
        ip in result and ip else.
    '''
    import re
    pattern = "^\w+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\w+$"
    regexp = re.compile(pattern)
    if regexp.match(regexp, answer):
        m = regexp.search(regexp, answer)
        ip = m.group(0)
        return ip
    else:
        raise RuntimeError

try:
    ip = parse_answer(answer)
except RuntimeError:
    print("Error, check your network configuration.")
    print("Aborting..")
    exit(1)

print("IP:", ip)

我写的。此代码旨在为您提供公共 IP 地址。如果它不能给你任何东西,它会抛出一个运行时错误。

这是错误:

Traceback(最近一次调用最后一次): 文件“./ippub”,第 27 行,在 ip = parse_answer(答案) 文件“./ippub”,第 19 行,在 parse_answer 如果正则表达式匹配(正则表达式,答案): TypeError: 'bytes' 对象不能被解释为整数

这意味着“答案”变量是字节,但我想在其中匹配一个 IP 地址,但我不能因为 python 类型系统:-)

有什么想法吗?非常感谢!

【问题讨论】:

    标签: regex python-3.x


    【解决方案1】:

    你有两个不同的问题。

    1. 您需要将answer 转换为字符串,即使answer 有一些有趣的字符不能很好地与utf-8 解码。

    2. 您正在错误地调用正则表达式 API。

    这是一个更正的版本,它使用chr 来解决问题 1,并使用正确的语法修复问题 2。

    #!/usr/bin/python
    from sys import exit
    import urllib.request
    import re
    
    
    def debug(txt):
        print(txt)
        exit(0)
    
    def parse_answer(answer):
        ''' Simple function to parse request's HTML result
            to find the ip in it. Raise RuntimeError if no 
            ip in result and ip else.
        '''
        answer = "".join([chr(x) for x in answer])
        pattern = "(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"
        regexp = re.compile(pattern)
        m = regexp.search(answer)
        if m:
            ip = m.group(0)
            return ip
        else:
            raise RuntimeError
    
    answer = urllib.request.urlopen("http://monip.org").read()
    
    try:
        ip = parse_answer(answer)
    except RuntimeError:
        print("Error, check your network configuration.")
        print("Aborting..")
        exit(1)
    
    print("IP:", ip)
    

    【讨论】:

      【解决方案2】:

      如果你尝试:

      print answer
      

      你会失败,因为它是在ISO-8859-1 中编码的。

      您应该先将其转换为UTF-8,然后再将其发送至parse_answer()

      answer = answer.encode('utf8')
      

      一旦你通过了这个障碍,你就会遇到另一个错误,它依赖于以下两行:

      if regexp.match(regexp, answer):
          m = regexp.search(regexp, answer) 
      

      因为regex 已经是一个编译模式,你不应该在上面的两个调用中将它作为参数发送!将代码更改为:

      if regexp.match(answer):
          m = regexp.search(answer) 
      

      它应该可以工作!


      对于梅林:

      import requests
      answer = requests.get("http://monip.org")
      print answer.text.encode('utf8')
      

      输出

      <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
      <html>
      <head>
      <title>MonIP.org v1.0</title>
      <META http-equiv="Content-type" content="text/html; charset=ISO-8859-1">
      </head>
      <P ALIGN="center"><FONT size=8><BR>IP : 50.184.3.115<br></font><font size=3><i>c-50-184-3-115.hsd1.ca.comcast.net</i><br></font><font size=1><br><br>Pas de proxy détecté - No Proxy detected</font></html>
      

      【讨论】:

      • @merlin2011 我确实测试了这个解决方案,我会在一分钟内发布代码(特别是为你;)
      • 谢谢。我很感激。您调用请求库的方法与 OP 的方法完全不同,因此您的答案现在更加有用。 +1。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多