【问题标题】:Python re regex matching issuePython重新正则表达式匹配问题
【发布时间】:2014-07-29 20:24:04
【问题描述】:

好的,请保持温和 - 这是我的第一个 stackoverflow 问题,我已经为此苦苦挣扎了几个小时。我确信答案很明显,盯着我的脸,但我放弃了。

我正在尝试从名称网站中抓取网页中的元素(即确定名称的性别)。

我写的python代码在这里:

import re
import urllib2

response=urllib2.urlopen("http://www.behindthename.com/name/janet")
html=response.read()
print html

patterns = ['Masculine','Feminine']

for pattern in patterns:
print "Looking for %s in %s<<<" % (pattern,html)

    if re.findall(pattern,html):
        print "Found a match!"
        exit
    else:
        print "No match!"

当我转储 html 时,我在那里看到 Feminine,但 re.findall 不匹配。我到底做错了什么?

【问题讨论】:

  • 你知道用这么简单的正则表达式你就可以做到if pattern in html?
  • 尽管有其他答案,但我看不出您给出的代码实际上不起作用的任何原因。如果你 print re.findall(pattern, html) 在循环中,你会得到什么?

标签: python html regex html-parsing expression


【解决方案1】:

Do not parse an HTML with regex,使用专门的工具 - HTML 解析器。

使用BeautifulSoup的示例:

from urllib2 import urlopen
from bs4 import BeautifulSoup

url = 'http://www.behindthename.com/name/janet'
soup = BeautifulSoup(urlopen(url))

print soup.select('div.nameinfo span.info')[0].text  # prints "Feminine"

或者,你可以find an element by text

gender = soup.find(text='Feminine')

然后,看看它是否是None(未找到):gender is None

【讨论】:

  • @alecxe 是的,该链接中的最佳答案非常清晰易懂。完全没有混乱。 (我正在为它添加书签以备后用。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 2016-11-27
  • 2013-04-05
  • 1970-01-01
相关资源
最近更新 更多