我正在尝试在hotstar上刮擦流行英语电影的数据
我下载了HTML源代码,我正在这样做:
from bs4 import BeautifulSoup as soup
page_soup = soup(open('hotstar.html'),'html.parser')
containers = page_soup.findAll("div",{"class":"col-xs-6 col-sm-4 col-md-3 col-lg-3 ng-scope"})
container = containers[0]
# To get video link
container.div.hs-cards-directive.article.a
我目前正在遇到错误:
NameError: name 'cards' is not defined
这些是HTML文件的前几行:
<div bindonce="" class="col-xs-6 col-sm-4 col-md-3 col-lg-3 ng-scope" ng-repeat="slides in gridcardData">
<hs-cards-directive cdata="slides" class="ng-isolate-scope" renderingdone="shownCard()">
<article class="card show-card" ng-class="{'live-sport-card':isLiveSportCard, 'card-active':btnRemoveShow,'tounament-tray-card':record.isTournament}" ng-click="cardeventhandler({cardrecord:record})" ng-init="init()" pdata="record" removecard="removecard" watched="watched">
<a href="http://www.hotstar.com/movies/step-up-revolution/1770016594" ng-href="/movies/step-up-revolution/1770016594" restrict-anchor="">
请帮助我!我在Windows上使用Python 3.6.3。
as(松散(在文档的下部部分中解释,tag.descendant
语法只是tag.find('descendant')
的方便快捷方式。
在您拥有名称不有效的python标识符的标签的情况下,无法使用快捷方式。 1 (也在您的标签上,其名称与BS4本身的方法相撞的标签,像<find>
标签。(
Python标识符只能具有字母,数字和下划线,而不是连字符。因此,当您写这篇文章时:
container.div.hs-cards-directive.article.a
…Python像这种数学表达式一样解析它:
container.div.hs - cards - directive.article.a
BeautifulSoup的div
节点没有名为hs
的后代,但这很好。它只是返回None
。但是然后尝试从该None
减去cards
,然后获得NameError
。
无论如何,在这种情况下,唯一的解决方案是不使用快捷方式并明确调用find
:
container.div.find('hs-cards-directive').article.a
或,如果对您的用例有意义,您可以跳到article
,因为捷径会找到任何后代,而不仅仅是指导孩子:
container.div.article.a
,但我认为在您的情况下这是不合适的;您只需要在特定的子节点下的文章,而不是所有可能的文章,对吗?
1。从技术上讲,实际上是可以使用快捷方式的,它不再是捷径了。如果您了解getattr(container.div, 'hs-cards-directive').article.a
的含义,那么您可以编写它,并且它将起作用……但是显然find
将更易读,更容易理解。