我正在尝试从 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())
但是,上面的代码返回一个空白列表。我究竟做错了什么?
问题就在这里:
firstVod = soup.findAll("tr",text=re.compile('rapidvideo'))
When BeautifulSoup
将应用您的文本正则表达式模式,它将使用.string属性 https://www.crummy.com/software/BeautifulSoup/bs4/doc/#string所有匹配的值tr
元素。现在.string
有这个重要的警告 -当一个元素有多个子元素时,.string
is None
:
如果一个标签包含多个内容,那么就不清楚是什么.string
应该参考,所以.string
被定义为None
.
因此,你没有结果。
您可以做的是检查实际文本tr
元素通过使用搜索功能 https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function并打电话.get_text()
:
soup.find_all(lambda tag: tag.name == 'tr' and 'rapidvideo' in tag.get_text())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)