【问题标题】:How to use BeautifulSoup and lxml together?如何一起使用 BeautifulSoup 和 lxml?
【发布时间】:2012-11-08 17:52:03
【问题描述】:

我是 Python 的新手。 BeautifulSoup和lxml如何搭配使用?

beautifulsoup website中推荐使用lxml作为解析器

def get_html():

        from bs4 import BeautifulSoup
        import lxml

        soup = BeautifulSoup(open("http://www.google.com"));
        #print(soup.prettify());
        print(soup.title);

if __name__ == '__main__':
        get_html()

【问题讨论】:

    标签: python html-parsing beautifulsoup lxml


    【解决方案1】:

    您在调用BeautifulSoup() 构造函数时指定解析器:

    import urllib2
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(urllib2.urlopen("http://www.google.com").read(), "lxml")
    

    【讨论】:

    • 第 6 行,在 get_feeds soup = BeautifulSoup(open("google.com"),"lxml"); IOError: [Errno 2] No such file or directory: 'google.com'
    • @Sop:我假设你已经设置了你的 url 加载。使用 requests 或 urllib2 之类的东西来加载页面进行解析。更新为使用urllib2 加载页面。
    • 谢谢!我是 Python 新手。为什么不能用lxml直接打开远程页面?
    • @Sop:是的,lxml 支持加载远程 URL,但 BeautifulSoup 不支持。由于您想使用 BeautifulSoup API,您必须自己加载 URL。
    猜你喜欢
    • 1970-01-01
    • 2019-03-26
    • 2012-07-03
    • 2015-11-18
    • 2018-03-03
    • 2016-07-27
    • 2020-03-14
    • 1970-01-01
    • 2021-12-24
    相关资源
    最近更新 更多