Skip to main content
 首页 » 编程设计

python之美丽汤 : Why is the "dlink_find(' a') ['href' ]"not working

2025年01月19日3752php

我正在尝试创建一个脚本来从一个特定的网站下载字幕。请阅读代码中的注释。 这是代码:

import requests 
from bs4 import BeautifulSoup 
 
count = 0 
usearch = input("Movie Name? : ") 
search_url = "https://www.yifysubtitles.com/search?q="+usearch 
base_url = "https://www.yifysubtitles.com" 
print(search_url) 
resp = requests.get(search_url) 
soup = BeautifulSoup(resp.content, 'lxml') 
for link in soup.find_all("div",{"class": "media-body"}):       #Get the exact class:'media-body' 
    imdb = link.find('a')['href']                               #Find the link in that class, which is the exact link we want 
    movie_url = base_url+imdb                                   #Merge the result with base string to navigate to the movie page 
    print("Movie URL : {}".format(movie_url))                   #Print the URL just to check.. :p 
 
    next_page = requests.get(movie_url)                         #Soup number 2 begins here, after navigating to the movie page 
    soup2 = BeautifulSoup(next_page.content,'lxml') 
    #print(soup2.prettify()) 
    for links in soup2.find_all("tr",{"class": "high-rating"}): #Navigate to subtitle options with class as high-rating 
        for flags in links.find("td", {"class": "flag-cell"}):  #Look for all the flags of subtitles with high-ratings 
            if flags.text == "English":                         #If flag is set to English then get the download link 
                print("After if : {}".format(links)) 
                for dlink in links.find("td",{"class": "download-cell"}):   #Once English check is done, navigate to the download class "download-cell" where the download href exists 
                    half_dlink = dlink.find('a')['href']                    #STUCK HERE!!!HERE'S THE PROBLEM!!! SOS!!! HELP!!! 
                    download = base_url + half_dlink 
                    print(download) 

我收到以下错误:

 File "C:/Users/PycharmProjects/WhatsApp_API/SubtitleDownloader.py", line 24, in <module> 
    for x in dlink.find("a"): 
TypeError: 'NoneType' object is not iterable 

请您参考如下方法:

只需将上面的行更改为:

for dlink in links.find("td",{"class": "download-cell"}):

为此:

for dlink in links.find_all("td",{"class": "download-cell"}): 

因为您在单个元素而不是列表上运行循环。

注意:唯一的区别是 find_all() 返回一个包含单个结果的列表,而 find() 只返回结果。

希望对您有所帮助! :)