将regexp应用于urlopen请求



我正试图在urlopen(req(的结果页上应用regexp过滤器:

from urllib.request import urlopen, Request
import re
from contextlib import closing
req = Request('https://yts-subs.com/movie-imdb/tt1483013')
req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36')
webpage = urlopen(req)
encoding = webpage.headers.get_content_charset('charset')
# page = str(webpage.read(), encoding)
page = webpage.read().decode('utf-8')
pattern = re.compile(r'<tr data-id=".*?"(?: class="((?:high|low)-rating)")?>s*<td class="rating-cell">s*.*</span>ns*</td>ns*<td class.*ns*<span.*>.*</span>ns*<span class="sub-lang">(.*)?</span>ns*</td>ns*<td>ns*<a href="(.*)?">'
,re.UNICODE)
print(pattern.findall(page))

但由于某些原因,它与任何东西都不匹配。模式应该是可以的,我单独测试了它,并且页面读取存在。由于怀疑有编码错误,我尝试str((或解码它,但没有成功。让我困惑的奇怪之处在于:如果我写一个中间文件并阅读它,它就会起作用。。。

在模式工作之前添加这个:

with open('temp.data', 'w') as data:
data.write(page)
page = ''
with open('temp.data','r') as data:
page=''.join(data.readlines())

很明显,我做错了什么,我希望得到一些提示!

好吧,原来问题出在我的regexp模式上。通过更精确地重写它,它起到了作用。以下是好的模式:

pattern = re.compile(r'<tr data-id=".*?"(?: class="((?:high|low)-rating)")?>s*<td class="rating-cell">s*.*</span>s*</td>s*<td class.*s*<span.*>.*</span>s*<span class="sub-lang">(.*)?</span>s*</td>s*<td>s*<a href="([^">]*)?')

和错误的比较:

pattern = re.compile(r'<tr data-id=".*?"(?: class="((?:high|low)-rating)")?>s*<td class="rating-cell">s*.*</span>ns*</td>ns*<td class.*ns*<span.*>.*</span>ns*<span class="sub-lang">(.*)?</span>ns*</td>ns*<td>ns*<a href="(.*)?">'
,re.UNICODE)

感谢您的帮助,我将调查已回答的备选方案!

最新更新