Python新手解析维基文本遭遇KeyError: 'revisions'问题求助
Hey there! That KeyError: 'revisions' pops up when the Wikipedia API doesn’t return the revisions data you’re expecting—usually because the page you’re requesting doesn’t exist, has been deleted, or is restricted. Let’s break down how to fix this:
Why This Happens
When you send a request for a page that doesn’t exist (like a typo in the title), the API returns a page object with a missing flag instead of the revisions field. Your code assumes revisions is always present, so it crashes when that’s not the case. There are also edge cases where a page exists but revisions aren’t accessible (e.g., deleted pages or restricted content).
Fixed Code with Error Handling
Here’s your updated code with checks to prevent the error, plus some optimizations for file writing:
def request_wiki_value(title=None, sentence=''): if title is None: title = input("No title entered.\nPlease enter a title: ") import requests import mwparserfromhell response = requests.get( 'https://en.wikipedia.org/w/api.php', params={ 'action': 'query', 'format': 'json', 'titles': title, 'prop': 'revisions', 'rvprop': 'content', } ).json() page = next(iter(response['query']['pages'].values())) # Check if the page doesn't exist if 'missing' in page: print(f"Error: The page '{title}' doesn't exist on Wikipedia. Double-check the spelling!") return # Check if revisions are unavailable if 'revisions' not in page: print(f"Error: Couldn't retrieve revisions for '{title}'. It may be deleted or restricted.") return # Proceed with parsing as before wikicode = page['revisions'][0]['*'] parsed_wikicode = mwparserfromhell.parse(wikicode) # Optimized file writing (safer & more efficient) with open("article.txt", "a", encoding='utf-8') as f: current_line = [] for ch in parsed_wikicode.strip_code(): if ch == '\n': if current_line: # Write the line without trailing newline f.write(''.join(current_line).rstrip('\n') + '\n') current_line = [] else: current_line.append(ch) # Handle any remaining content after the last newline if current_line: f.write(''.join(current_line).rstrip('\n') + '\n')
Key Changes Explained
- Existence Checks: We first check for the
missingkey to catch invalid page titles, and verifyrevisionsexists before accessing it. - File Writing Optimization: Using a
withstatement ensures the file is properly closed automatically, and building lines in memory instead of appending character-by-character is faster and cleaner.
Quick Tip
Double-check your page titles—Wikipedia titles are case-sensitive for proper nouns (e.g., "Python (programming language)" is the correct title for the language page, not just "Python" if you want to avoid redirects).
内容的提问来源于stack exchange,提问作者LidorTubul

