python - re.search 网页源中包含回车符的中间字符串会导致 Python 中出现错误

标签 python youtube mechanize python-2.6

使用Python 2.6.6

我正在尝试使用 mechanize 浏览器获取 YouTube 链接的标题,虽然它确实可以处理指向实际视频的链接,但链接到 channel 页面或其播放列表等会导致其崩溃。

相关代码段:

ytpage = br.open(ytlink).read()
yttitle = re.search('<title>(.*)</title>', ytpage)
yttitle = yttitle.group(1)

错误:

yttitle = yttitle.group(1) AttributeError: 'NoneType' object has no attribute 'group'

我能看到的唯一区别是直接视频链接将标题标签放在 a single line 上。在源代码中,而其他所有 YouTube 页面似乎都放置 a carriage return/newline在标题标签的中间。

假设这是问题所在,有人知道我如何绕过回车符吗?

干杯。

最佳答案

您可以使用 re.DOTALL 标志,这将使 . 匹配包括换行符在内的所有内容。

Documentation

所以你的第二行代码应该如下所示:

yttitle = re.search('<title>(.*)</title>', ytpage, re.DOTALL)

顺便说一句,从网页中提取数据可能更容易使用 Beautiful Soup .

关于python - re.search 网页源中包含回车符的中间字符串会导致 Python 中出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33437727/

相关文章:

iframe - 嵌入式YouTube iframe不再自动播放

android - BasicNetwork.performRequest : Unexpected response code 403 for https://www. googleapis.com/youtube/v3/playlistItems?

javascript - YouTube - 将 Assets ID 链接到视频 ID

utf-8 - Mechanize 将 - char 转换为 -

Python Mechanize 动态下拉选择

python - Python 中的 Mechanize - 提交后重定向不起作用

python - 为什么我会收到无效的语法错误?

Python打印二维数组中用户定义的行

Python Pandas : extract date and time from timestamp

Python - 匹配列表中单词的字母