Python中正则表达式无法捕获模式

2024-04-26 04:19:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我基本上是从一个特定的页面抓取数据。 我有这个密码:

regex = '<ul class="w462">(.*?)</ul>'

opener.open(baseurl)
urllib2.install_opener(opener)

... rest of code omitted ...

requestData = urllib2.urlopen(request)
htmlText = requestData.read()

pattern = re.compile(regex)
movies = re.findall(pattern, htmlText)

# Lines below will always returns empty.
if not movies:
    print "List is empty. Printing source instead...", "\n\n"
    print htmlText
else:
    print movies

htmlText的内容:

<ul class="w462">

... bunch of <li>s (the content i want to retrieve).

</ul>

htmlText包含正确的源代码(我尝试按住ctrl+F组合键,并且可以验证它是否包含所需的ul元素)。只是我的正则表达式无法获得所需的内容。你知道吗

我试着用这个来代替:

movies = re.findall(r'<ul class="w462">(.*?)</ul>', htmlText)

有人知道哪里出了问题吗?你知道吗


Tags: ofreopenerurllib2moviesulclassregex
1条回答
网友
1楼 · 发布于 2024-04-26 04:19:40

默认情况下,regexp中的.匹配除换行符以外的任何字符。所以您的regexp不能匹配跨越多行(至少包含一个换行符)的任何内容。你知道吗

将编译行更改为:

pattern = re.compile(regex, re.DOTALL)

改变.的意思。使用re.DOTALL.将匹配任何字符(包括换行符)。你知道吗

相关问题 更多 >

    热门问题