基于主题爬取Books.toscrape.com书籍:URL获取及代码报错求助
Web Scraping Solution for Books.toscrape.com
Problem Recap
- Scrape all books (across multiple pages) for a user-specified topic from Books.toscrape.com
- First verify if the topic exists on the site
- Display book titles and their corresponding prices
- Original code threw an "URL undefined" error because the topic matching logic was incorrect
Fixed Working Code
import requests from bs4 import BeautifulSoup topic = input("What topic do you want to see the available books for? ").strip().lower() base_url = "http://books.toscrape.com/" response = requests.get(base_url) soup = BeautifulSoup(response.content, 'html.parser') # Target category links in the sidebar navigation category_links = soup.select('div.side_categories ul li a') topic_url = None for link in category_links: # Clean and normalize link text for accurate matching link_text = link.get_text(strip=True).lower() if topic == link_text: # Build full topic page URL from relative path topic_url = base_url + link['href'] break if not topic_url: print(f"Topic '{topic}' does not exist on the site.") else: print(f"Fetching books for topic: {topic.capitalize()}") current_page_url = topic_url # Loop through all pages of the topic while current_page_url: page_response = requests.get(current_page_url) page_soup = BeautifulSoup(page_response.content, 'html.parser') # Extract book titles and prices book_items = page_soup.select('article.product_pod') for item in book_items: book_title = item.h3.a['title'] book_price = item.select_one('p.price_color').get_text(strip=True) print(f"- {book_title}: {book_price}") # Check for next page and update URL next_page_btn = page_soup.select_one('li.next a') if next_page_btn: # Fix relative path for pagination links current_page_url = base_url + 'catalogue/category/books/' + next_page_btn['href'] else: current_page_url = None
Key Fixes & Improvements
- Accurate Topic Matching: Instead of checking against the raw link object, extract and clean the link text to match user input case-insensitively
- Undefined URL Handling: Added a check to catch non-existent topics before proceeding, eliminating the "URL undefined" error
- Valid URL Construction: Combines the base site URL with relative hrefs to form fully functional page URLs
- Multi-page Support: Implements loop to navigate through all pagination pages of the topic
- Robust Element Selection: Uses CSS selectors (
select/select_one) for more reliable targeting of category links and book elements
Critical Logic Explanation
The site's category links are nested in the sidebar
div.side_categoriessection. By targeting this specific area, we avoid irrelevant links elsewhere on the homepage. Pagination links use relative paths that need adjustment to form valid full URLs, which is handled in the next page check.
内容的提问来源于stack exchange,提问作者Snooch
相关产品推荐
相关产品推荐

