[英]Python: HTML regex not matching
I have this code: 我有以下代码:
reg = re.search('<div class="col result_name">(.*)</div>', html)
print 'Value is', reg.group()
Where 'html' contains something like this: 其中“ html”包含以下内容:
<div class="col result_name">
<h4>Blah</h4>
<p>
blah
</p>
</div>
But it's not returning anything. 但是它没有返回任何东西。
Value is
Traceback (most recent call last):
File "run.py", line 37, in <module>
print 'Value is', reg.group()
Don't use regex to parse html. 不要使用正则表达式来解析html。 Use a html parser 使用HTML解析器
import lxml.html
doc = lxml.html.fromstring(your_html)
result = doc.xpath("//div[@class='col result_name']")
print result
Obligatory link: 强制链接:
RegEx match open tags except XHTML self-contained tags RegEx匹配XHTML自包含标签以外的打开标签
点不一定与RE中的换行符匹配, DOTALL
您需要DOTALL
标志(?s)
。
http://docs.python.org/library/re.html : http://docs.python.org/library/re.html :
The special characters are: 特殊字符为:
'.' '。' (Dot.) In the default mode, this matches any character except a newline . (点)在默认模式下,它匹配除换行符之外的任何字符。 If the DOTALL flag has been specified, this matches any character including a newline. 如果指定了DOTALL标志,则它匹配包括换行符在内的任何字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.