BeautifulSoup 解析 XML 不工作

1 投票
1 回答
1786 浏览
提问于 2025-04-18 03:46

我正在尝试用 BeautifulSoup 来解析一个 XML 页面,但不知为什么它找不到 XML 解析器。我觉得这不是路径的问题,因为我之前用过 lxml 来解析网页,只是没有解析过 XML。以下是我的代码:

from bs4 import *
import urllib2
import lxml
from lxml import *


BASE_URL = "http://auctionresults.fcc.gov/Auction_66/Results/xml/round/66_115_database_round.xml"

proxy = urllib2.ProxyHandler({'http':'http://myProxy.com})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
page = urllib2.urlopen(BASE_URL)

soup = BeautifulSoup(page,"xml") 

print soup

我可能漏掉了什么简单的东西,但我在这里找到的所有关于用 BS 解析 XML 的问题都是关于 bs3 的,而我用的是 bs4,它解析 XML 的方法不一样。谢谢。

1 个回答

1

如果你已经安装了 lxml,那么可以直接把它当作 BeautifulSoup 的解析器来使用,像下面这样。

代码:

from bs4 import BeautifulSoup as bsoup
import requests as rq

url = "http://auctionresults.fcc.gov/Auction_66/Results/xml/round/66_115_database_round.xml"
r = rq.get(url)

soup = bsoup(r.content, "lxml")
print soup

结果:

<html><body><dataroot xmlns:od="urn:schemas-microsoft-com:officedata" xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" xsi:nonamespaceschemalocation="66_database.xsd"><all_bids>
<auction_id>66</auction_id>
<auction_description>Advanced Wireless Services</auction_description>
... really long list follows...
[Finished in 34.9s]

如果这对你有帮助,请告诉我们。

撰写回答