【问题标题】:Soup works on one IMBD page but not on another. How to solve?Soup 在一个 IMDB 页面上有效,但在另一个页面上无效。怎么解决?
【发布时间】:2020-08-24 18:55:47
【问题描述】:
url1 = "https://www.imdb.com/user/ur34087578/watchlist"
url = "https://www.imdb.com/search/title/?groups=top_1000&ref_=adv_prv"

results1 = requests.get(url1, headers=headers)
results = requests.get(url, headers=headers)
soup1 = BeautifulSoup(results1.text, "html.parser")
soup = BeautifulSoup(results.text, "html.parser")

movie_div1 = soup1.find_all('div', class_='lister-item-content')
movie_div = soup.find_all('div', class_='lister-item mode-advanced')
#using unique tag for each movie in the respective link

print(movie_div1)
#empty list
print(movie_div)
#gives perfect list

为什么 movie_div1 给出一个空列表?我无法识别 URL 结构中的任何差异以表明代码应该不同。感谢所有潜在客户。

【问题讨论】:

  • 你想从你的监视列表中提取什么?当我在网络浏览器中打开网页时,我什至找不到带有 lister-item-content 类的 div 标签。
  • @ritiek 你打开检查然后尝试搜索了吗?
  • 是的,它显示在检查中。

标签: python html web beautifulsoup web-crawler


【解决方案1】:

不幸的是,您想要的 div 由 javascript 代码处理,因此您无法通过 scraping 原始 html 请求获得。

您可以通过浏览器获取的请求 json 来获取您想要的电影,您无需使用 beautifulsoup 抓取代码,从而使您的脚本更快。

第二个选项是使用 Selenium。

祝你好运。

【讨论】:

    【解决方案2】:

    正如@SakuraFreak 提到的,您可以解析收到的 JSON。然而,这个 JSON 响应嵌入在 HTML 本身中,稍后由浏览器 JS 转换为 HTML(这就是你看到的 <div class="lister-item-content">...</div>

    例如,您可以通过以下方式从 HTML 中提取 JSON 内容以显示关注列表中的电影/节目名称:

    import requests
    from bs4 import BeautifulSoup
    import json
    
    url = "https://www.imdb.com/user/ur34087578/watchlist"
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    
    details = str(soup.find('span', class_='ab_widget'))
    
    json_initial = "IMDbReactInitialState.push("
    json_leftover = ");\n"
    
    json_start = details.find(json_initial) + len(json_initial)
    details = details[json_start:]
    json_end = details.find(json_leftover)
    
    json_data = json.loads(details[:json_end])
    
    imdb_titles = json_data["titles"]
    for item in imdb_titles.values():
        print(item["primary"]["title"])
    

    【讨论】:

    • 您好,非常感谢您花时间提出解决方案。我只是有一个小小的疑问。在您的循环中,您直接提取了“标题”而没有明确定义它们的位置(以前在普通的“HTML”中,我必须指定 class..h3..tag..unique 标识符等等才能获得位置) .此外,当我在检查中搜索“标题”时,我得到了这段 javascript (imgur.com/a/1CiGCOq)。您是否查看了汤的印刷品以找到电影名称的标签?
    • 是的,您在发布的图片中看到的 JSON 内容正是代码从收到的网页响应内容中提取的内容。然后它将提取的 JSON 内容转换为 python 字典(通过调用 json.loads),然后从该字典中索引“标题”的值(其中还包含有关 IMDB 关注列表中的节目/电影的相关信息)。所以,上面提取或索引“titles”的值不是在 BeautifulSoup 对象(我认为你认为)上,而是在一个有点不同的 python 字典上。是的,我查看了汤的输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2022-01-14
    • 2012-08-22
    • 1970-01-01
    相关资源
    最近更新 更多