如何确保 re.findall() 停在正确的位置? [英] How do I ensure that re.findall() stops at the right place?

查看:36
本文介绍了如何确保 re.findall() 停在正确的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

a='aaaaaa2aaa3'进口重新re.findall(r'<(title)>(.*)<(/title)>', a)

结果是:

[('title', 'aaa</title><title>aaa2</title><title>aaa3', '/title')]

如果我设计了一个爬虫来获取网站的标题,我最终可能会得到这样的东西,而不是网站的标题.

我的问题是,如何将 findall 限制为单个 ?

解决方案

如果您只想要一个匹配项,请使用 re.search 而不是 re.findall:

<预><代码>>>>s = '<title>aaa</title><title>aaa2</title><title>aaa3</title>'>>>进口重新>>>re.search('<title>(.*?)</title>', s).group(1)'啊'

如果您想要所有标签,那么您应该考虑将其更改为非贪婪(即 - .*?):

print re.findall(r'(.*?)', s)# ['aaa', 'aaa2', 'aaa3']

但真的考虑使用 BeautifulSoup 或 lxml 或类似的来解析 HTML.

Here is the code I have:

a='<title>aaa</title><title>aaa2</title><title>aaa3</title>'
import re
re.findall(r'<(title)>(.*)<(/title)>', a)

The result is:

[('title', 'aaa</title><title>aaa2</title><title>aaa3', '/title')]

If I ever designed a crawler to get me titles of web sites, I might end up with something like this rather than a title for the web site.

My question is, how do I limit findall to a single <title></title>?

解决方案

Use re.search instead of re.findall if you only want one match:

>>> s = '<title>aaa</title><title>aaa2</title><title>aaa3</title>'
>>> import re
>>> re.search('<title>(.*?)</title>', s).group(1)
'aaa'

If you wanted all tags, then you should consider changing it to be non-greedy (ie - .*?):

print re.findall(r'<title>(.*?)</title>', s)
# ['aaa', 'aaa2', 'aaa3']     

But really consider using BeautifulSoup or lxml or similar to parse HTML.

这篇关于如何确保 re.findall() 停在正确的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆