【问题标题】:Python regex issuesPython 正则表达式问题
【发布时间】:2014-11-29 11:56:48
【问题描述】:

我试图通过使用 urlib 扫描页面并使用正则表达式查找代理来使用 python 从site 中获取代理。

页面上的代理如下所示:

<a href="/ip/190.207.169.184/free_Venezuela_proxy_servers_VE_Venezuela">190.207.169.184</a></td><td>8080</td><td>

我的代码如下所示:

for site in sites:
content = urllib.urlopen(site).read()
e = re.findall("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\<\/\a\>\<\/td\>\<td\>\d+", content)
#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+

for proxy in e:
    s.append(proxy)
    amount += 1

正则表达式:

\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\<\/\a\>\<\/td\>\<td\>\d+

我知道代码有效,但正则表达式错误。

知道如何解决这个问题吗?

编辑:http://www.regexr.com/ 似乎我的正则表达式没问题?

【问题讨论】:

  • 查看lxmlbeautifulsoup。对 html 使用正则表达式是一种 hack。
  • 不要逃避 &lt;,&gt;,a,/ regex101.com/r/xB5sT0/2
  • 此外,如果您不想转义正则表达式中的每个 \,则需要使用原始字符串:在字符串前面加上 r,例如r"\d{1, 3}"
  • 该站点甚至具有“导出为 JSON”和“导出为文本”功能。也许你骑错了马?

标签: python html regex web-scraping html-parsing


【解决方案1】:

一种选择是使用 HTML 解析器来查找 IP 地址和端口。

示例(使用BeautifulSoup HTML 解析器):

import re
import urllib2
from bs4 import BeautifulSoup

data = urllib2.urlopen('http://letushide.com/protocol/http/3/list_of_free_HTTP_proxy_servers')

IP_RE = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
PORT_RE = re.compile(r'\d+')

soup = BeautifulSoup(data)
for ip in soup.find_all('a', text=IP_RE):
    port = ip.parent.find_next_sibling('td', text=PORT_RE)
    print ip.text, port.text

打印:

80.193.214.231 3128
186.88.37.204 8080
180.254.72.33 80
201.209.27.119 8080
...

这里的想法是找到所有与\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}正则表达式匹配的文本的a标签。对于每个链接,找到与 \d+ 文本匹配的父级的下一个 td 兄弟姐妹。


另外,由于您知道表格结构以及有 IP 和端口的列,您可以通过索引从每一行获取单元格值,无需在此处深入研究正则表达式:

import urllib2
from bs4 import BeautifulSoup

data = urllib2.urlopen('http://letushide.com/protocol/http/3/list_of_free_HTTP_proxy_servers')

soup = BeautifulSoup(data)
for row in soup.find_all('tr', id='data'):
    print [cell.text for cell in row('td')[1:3]]

打印:

[u'80.193.214.231', u'3128']
[u'186.88.37.204', u'8080']
[u'180.254.72.33', u'80']
[u'201.209.27.119', u'8080']
[u'190.204.96.72', u'8080']
[u'190.207.169.184', u'8080']
[u'79.172.242.188', u'8080']
[u'1.168.171.100', u'8088']
[u'27.105.26.162', u'9064']
[u'190.199.92.174', u'8080']
...

【讨论】:

    猜你喜欢
    • 2010-10-20
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    相关资源
    最近更新 更多