【问题标题】:Beautiful Soup KeyError 'href' but the definitely exist美丽的汤 KeyError 'href' 但肯定存在
【发布时间】:2021-09-23 21:35:31
【问题描述】:

试图从网站中提取所有链接。我得到“KeyError:'href'”,但据我了解,这仅适用于存在不存在 href 的标签时。但是,当我查看汤对象时,每个标签都有一个 href。所以我不明白为什么我会看到这个错误。我查了很多,每个人总是只提到没有href的标签。

from bs4 import BeautifulSoup
from datetime import datetime
import pandas as pd
import requests

page_count = 1
catalog_page = f"https://40kaudio.com/page/{str(page_count)}/?s"

while page_count < 4:
    print(f"Begin Book Scrape from {catalog_page}")
    # Soup opens the page.
    open_page = requests.get(catalog_page)
    # We create a soup object that has all the page stuff in it
    soup = BeautifulSoup(open_page.content, "html.parser")
    # We iterate through that soup object and pull out anything with a class of "title-post"
    for link in soup.find_all('h2', "title-post"):
        print(link['href'])

else:
    print('By the Emperor!')

【问题讨论】:

  • 请修正缩进

标签: python web-scraping beautifulsoup href


【解决方案1】:

link 中没有 href 标记。但是,link 中有一个a 标记,a 标记中有一个href 属性。

<a href="https://40kaudio.com/justin-d-hill-cadia-stands-audiobook/" rel="bookmark">Justin D. Hill &#8211; Cadia Stands Audiobook</a>
for link in soup.find_all('h2', "title-post"):
    print(link.a['href'])

不要忘记在 while 循环中增加 page_count

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 2016-12-18
    • 2011-11-15
    • 2018-07-31
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    相关资源
    最近更新 更多