python - 如何组合所有 3 合 1 re.findall() ??(python 2.7 && 正则表达式)

标签 python html regex html-parsing

Filter1=re.findall(r'<span (.*?)</span>',PageSource) 
Filter2=re.findall(r'<a href=.*title="(.*?)" >',PageSource) 
Filter3=re.findall(r'<span class=.*?<b>(.*?)</b>.*?',PageSource)

如何用 1 行代码做到这一点......就像这样:

Filter=re.findall(r'  ',PageSource)

我尝试过这种方法:

Filter=re.findall(r'<span (.*?)</span>'+
                  r'<a href=.*title="(.*?)" >'+
                  r'<span class=.*?<b>(.*?)</b>.*?',PageSource)

但是它不起作用。

最佳答案

使用 HTML 解析器怎么样?

示例,使用 BeautifulSoup :

from bs4 import BeautifulSoup

data = "your HTML here"
soup = BeautifulSoup(data)

span_texts = [span.text for span in soup.find_all('span')]
a_titles = [a['title'] for a in soup.find_all('a', title=True)]
b_texts = [b.text for b in soup.select('span[class] > b')]

result = span_texts + a_titles + b_texts

演示:

>>> from bs4 import BeautifulSoup
>>> 
>>> data = """
... <div>
...     <span>Span's text</span>
...     <a title="A title">link</a>
...     <span class="test"><b>B's text</b></span>
... </div>
... """
>>> soup = BeautifulSoup(data)
>>> 
>>> span_texts = [span.text for span in soup.find_all('span')]
>>> a_titles = [a['title'] for a in soup.find_all('a', title=True)]
>>> b_texts = [b.text for b in soup.select('span[class] > b')]
>>> 
>>> result = span_texts + a_titles + b_texts
>>> print result
[u"Span's text", u"B's text", 'A title', u"B's text"]
<小时/>

除此之外,您的正则表达式非常不同并且具有不同的目的 - 我不会尝试挤压不可挤压的,将它们分开并将结果合并到一个列表中。

关于python - 如何组合所有 3 合 1 re.findall() ??(python 2.7 && 正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28618852/

相关文章:

java - 如何在正则表达式中捕获多个组?

Python正则表达式搜索,匹配不匹配

c# - 如何使用模式从字符串中获取字符串列表?

python - 运行子文件夹中的脚本

javascript - 弹出窗口内的关闭按钮不响应(点击事件上的 jQuery)

Python 另一个字典中的两个字典另一个字典中的两个字典

php - 使用 PHP 获取图像文件路径并以 HTML 显示

javascript - 如何将 javascript 参数从 HTML 表格单元格发送到 DOM 元素?

python - OpenCV 读取视频文件在 Python 中非常慢

python - 在python中比较超过最大递归深度?