【问题标题】:im trying to get proxies using regex python out of a web page我试图从网页中使用正则表达式 python 获取代理
【发布时间】:2013-04-21 20:43:15
【问题描述】:
import urllib.request
import re
page = urllib.request.urlopen("http://www.samair.ru/proxy/ip-address-01.htm").read()
re.findall('\d+\.\d+\.\d+\.\d+', page)

我不明白为什么会这样说:

文件“C:\Python33\lib\re.py”,第 201 行,在 findall 中 返回_compile(模式,标志).findall(字符串) TypeError: can't use a string pattern on a bytes-like object

【问题讨论】:

标签: python python-3.x urllib


【解决方案1】:
import urllib
import re
page = urllib.urlopen("http://www.samair.ru/proxy/ip-address-01.htm").read()
print re.findall('\d+\.\d+\.\d+\.\d+', page)

工作并给了我结果:

['056.249.66.50', '100.44.124.8', '103.31.250.115', ...

编辑

  • 这适用于 python2.7

【讨论】:

  • 哦,我有 python 3.3.0
  • 检查你的遮阳篷是否在我的 python 中
  • 感谢它的工作原理,但你知道如何在每个代理将 e 在不同的行之后做到这一点。
  • "\n".join(list_of_proxies)
  • 但是如果我需要带有 IP 地址的端口号?
【解决方案2】:

读取urllib.request.urlopen返回的类文件对象的结果是一个字节对象。您可以将其解码为 un​​icode 字符串并使用 unicode 正则表达式:

>>> re.findall('\d+\.\d+\.\d+\.\d+', page.decode('utf-8'))
['056.249.66.50', '100.44.124.8', '103.31.250.115', '105.236.180.243', '105.236.21.213', '108.171.162.172', '109.207.61.143', '109.207.61.197', '109.207.61.202', '109.226.199.129', '109.232.112.109', '109.236.220.98', '110.196.42.33', '110.74.197.141', '110.77.183.64', '110.77.199.111', '110.77.200.248', '110.77.219.154', '110.77.219.2', '110.77.221.208']

...或使用字节正则表达式:

>>> re.findall(b'\d+\.\d+\.\d+\.\d+', page)
[b'056.249.66.50', b'100.44.124.8', b'103.31.250.115', b'105.236.180.243', b'105.236.21.213', b'108.171.162.172', b'109.207.61.143', b'109.207.61.197', b'109.207.61.202', b'109.226.199.129', b'109.232.112.109', b'109.236.220.98', b'110.196.42.33', b'110.74.197.141', b'110.77.183.64', b'110.77.199.111', b'110.77.200.248', b'110.77.219.154', b'110.77.219.2', b'110.77.221.208']

取决于您喜欢使用的数据类型。

【讨论】:

    猜你喜欢
    • 2020-09-28
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    相关资源
    最近更新 更多