【问题标题】:regex not working in bs4正则表达式在 bs4 中不起作用
【发布时间】:2017-08-19 13:27:27
【问题描述】:

我正在尝试从 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())

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

【问题讨论】:

  • NB:findAll 在 bs4 中似乎已重命名为 find_all。 (显然,bs3 版本一直保留,但无论如何我都会更新您的代码。)find_all 函数签名也没有text 参数,而是string 参数。

标签: python regex urllib2 bs4


【解决方案1】:

问题出在这里:

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

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

如果一个标签包含不止一个东西,那么.string应该指代什么就不清楚了,所以.string被定义为None

因此,您没有结果。

您可以通过使用searching function 并调用.get_text() 来检查tr 元素的实际文本:

soup.find_all(lambda tag: tag.name == 'tr' and 'rapidvideo' in tag.get_text())

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2014-09-12
    • 2012-02-13
    相关资源
    最近更新 更多