Python:使用正则表达式在一些网站标签之间查找句子

发布于 2024-12-15 04:20:39 字数 731 浏览 3 评论 0原文

我想在 ...class="question-hyperlink"> 标签之间找到一个句子。 使用此代码:

import urllib2
import re

response = urllib2.urlopen('https://stackoverflow.com/questions/tagged/python')
html = response.read(20000)

a = re.search('question-hyperlink', html)
print html[a.end()+3:a.end()+100]

我得到:

DF5 for Python: high level vs low level interfaces. h5py</a></h3>        <div class="excerpt">

如何在下一个 < 处停止? 我如何找到下一句话? 我想用正则表达式来做。

编辑 致反对票的人: 我想像他那样做: RegEx 匹配开放标记(XHTML 自包含标记除外)

I want to find a sentence between the ...class="question-hyperlink"> tags.
With this code:

import urllib2
import re

response = urllib2.urlopen('https://stackoverflow.com/questions/tagged/python')
html = response.read(20000)

a = re.search('question-hyperlink', html)
print html[a.end()+3:a.end()+100]

I get:

DF5 for Python: high level vs low level interfaces. h5py</a></h3>        <div class="excerpt">

How can I stop at the next < ?
And how do I find the next sentence?
I want to do it with regex.

EDIT
To the downvoters:
I want to do it like he does:
RegEx match open tags except XHTML self-contained tags

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Spring初心 2024-12-22 04:20:39

如果您必须使用正则表达式来完成此操作,请尝试如下操作:

a = re.finditer('<a.+?question-hyperlink">(.+?)</a>', html)
for m in a: 
    print m.group(1)

仅供参考,此代码执行相同的操作,但以更健壮的方式:

doc = BeautifulSoup(html)
for a in doc.findAll('a', 'question-hyperlink'):
    print a.text

If you must do it with regular expressions, try something like this:

a = re.finditer('<a.+?question-hyperlink">(.+?)</a>', html)
for m in a: 
    print m.group(1)

Just for the reference, this code does the same, but in a far more robust way:

doc = BeautifulSoup(html)
for a in doc.findAll('a', 'question-hyperlink'):
    print a.text
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文