如何通过放置“”来刮取不存在的值?

2024-04-30 06:37:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在IMDB网站上抓拍电影。在抓取时,我能够抓取电影的证书,即它是被禁止的,还是PG-13,还是R,但对于某些电影,证书似乎不存在,所以我如何放置“-”,对于那些电影,我尝试使用下面代码中所示的if-else循环,但似乎不起作用。附加代码和屏幕截图以供参考。我正在使用BeautifulSoup库进行刮削。我们有没有办法把“-”或“NA”放在不存在的地方

if data.find_all("span",{"class":"certificate"}):
    certificate=[c.get_text() for c in data.find_all("span",{"class":"certificate"})]
else:
    certificate="-"

enter image description here


Tags: 代码dataif电影屏幕网站certificateall
1条回答
网友
1楼 · 发布于 2024-04-30 06:37:10

搜索span类的父类(<p class="text-muted">),然后检查类为certificatespan标记是否存在

from bs4 import BeautifulSoup
import requests

url = "https://www.imdb.com/search/title/?genres=action&genres=Action"

response = requests.get(url, headers={"user-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(response.text, 'lxml')

for p in soup.find_all("p", {"class": "text-muted"}):
    if p.find("span", {"class":"certificate"}):
        certificate = p.span.get_text()
    else:
        certificate = "-"
    print(certificate)
TV-MA
-
PG-13
-
TV-14
-
PG-13
...
...

相关问题 更多 >