Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式不捕获模式_Python_Regex_Python 2.7 - Fatal编程技术网

Python正则表达式不捕获模式

Python正则表达式不捕获模式,python,regex,python-2.7,Python,Regex,Python 2.7,我基本上是从一个特定的页面抓取数据。 我有以下代码: 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.compil

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

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
regex='
    (.*)
' opener.open(baseurl) urllib2.install_opener(opener) ... 代码的其余部分被省略。。。 requestData=urllib2.urlopen(请求) htmlText=requestData.read() pattern=re.compile(regex) movies=re.findall(模式,htmlText) #下面的行将始终返回空。 如果不是电影: 打印“列表为空。改为打印源…”,“\n\n” 打印htmlText 其他: 印刷电影
htmlText的内容:

<ul class="w462">

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

</ul>
    ... 一堆
  • s(我要检索的内容)。
htmlText包含正确的源代码(我尝试按住ctrl+F组合键,可以验证它是否包含所需的ul元素。这只是因为我的正则表达式无法获取所需的内容

我试着用这个来代替:

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

有人知道出了什么问题吗?

默认情况下,regexp中的
匹配除新行以外的任何字符。因此,您的regexp不能匹配跨越多行(至少包含一行新行)的任何字符

将编译行更改为:

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

要更改
的含义,使用
re.DOTALL
将匹配任何字符(包括换行符)。

为什么不使用HTML解析器来解析HTML?无论如何,通过control+F查找的数据可能是由某些JavaScript创建的,我认为regex无法捕获。(不要引用我,我可能完全错了)。考虑一下。我从来没有使用过它,但我认为这是正确的工具,对于花哨的解析,你肯定想要一个真正的HTML解析模块,但是对于简单的任务,像ReXEPS是很好的。不要理会仇恨者——LOL;正则表达式在解析标记语言的上下文中从来都不合适。从来没有。嘿嘿-@username55被卡住了,现在不稳定了。这是一个Python问题:“实用性胜过纯度”;-)@user2618501是的,它们有时是合适的。如果你处理的是有限的HTML,那没关系。别在这件事上那么学究气了:p