Python2转Python3:已弃用的AppUrlOpener与FancyURLopener替代方案咨询
Hey there! Let's get that User-Agent setup sorted for your XML download script—Python 3 did away with urllib.request.FancyURLopener, so we need a modern alternative that plays nice with the current urllib APIs.
Option 1: Set a Global Custom Opener (Match Your Original Workflow)
This replicates what your old AppUrlOpener was doing—setting a default User-Agent for all urllib requests in your script. Here's how to do it:
First, keep your exact User-Agent string:
USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'
Then create and install a custom opener that uses this header:
import urllib.request # Build a custom opener instance opener = urllib.request.build_opener() # Attach your User-Agent to the opener's default headers opener.addheaders = [('User-agent', USER_AGENT)] # Install this opener as the default for all urllib.request calls urllib.request.install_opener(opener)
Now whenever you call urllib.request.urlopen() later in your code, it will automatically send the correct User-Agent header—no need to mess with the internal _urlopener variable (which was never meant to be modified directly anyway!).
Option 2: Per-Request Headers (More Flexible)
If you only need the custom User-Agent for specific requests (not all of them), you can wrap each URL in a Request object with the headers included:
import urllib.request USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36' # For each target URL, create a Request with your custom headers url = "https://your-target-xml-url.com" req = urllib.request.Request(url, headers={'User-Agent': USER_AGENT}) # Open the request and process the XML data with urllib.request.urlopen(req) as response: xml_content = response.read() # Proceed with your XML conversion logic here
This approach is great if you might need different headers for different requests later on.
Why Your Original Attempt Didn't Work
urlopen() is a function that makes a single request—it can't be assigned to _urlopener like your old AppUrlOpener instance. The modern Python 3 way is either using install_opener for global defaults or Request objects for per-call customization.
内容的提问来源于stack exchange,提问作者Ian Waller

