正则表达式在 bs4 中不起作用

regex not working in bs4

我正在尝试从 watchseriesfree.to 网站上的特定文件托管程序中提取一些链接。在下面的例子中,我想要 rapidvideo 链接,所以我使用正则表达式过滤掉那些文本包含 rapidvideo

的标签
import re
import urllib2
from bs4 import BeautifulSoup

def gethtml(link):
    req = urllib2.Request(link, headers={'User-Agent': "Magic Browser"})
    con = urllib2.urlopen(req)
    html = con.read()
    return html


def findLatest():
    url = "https://watchseriesfree.to/serie/Madam-Secretary"
    head = "https://watchseriesfree.to"

    soup = BeautifulSoup(gethtml(url), 'html.parser')
    latep = soup.find("a", title=re.compile('Latest Episode'))

    soup = BeautifulSoup(gethtml(head + latep['href']), 'html.parser')
    firstVod = soup.findAll("tr",text=re.compile('rapidvideo'))

    return firstVod

print(findLatest())

但是,上面的代码returns是一个空白列表。我做错了什么?

问题出在这里:

firstVod = soup.findAll("tr",text=re.compile('rapidvideo'))

BeautifulSoup 应用您的文本正则表达式模式时,它将使用所有匹配的 tr 元素的 .string attribute 值。现在,.string 有一个重要的警告 - 当一个元素有多个子元素时,.stringNone

If a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to be None.

因此,您没有结果。

您可以通过使用 searching function 并调用 .get_text():

来检查 tr 元素的实际文本
soup.find_all(lambda tag: tag.name == 'tr' and 'rapidvideo' in tag.get_text())