【发布时间】: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