【问题标题】:BeautifulSoup HTML parsing function won't work twiceBeautifulSoup HTML解析功能不会工作两次
【发布时间】:2019-05-31 16:31:15
【问题描述】:

我正在使用 selenium 和 bs4 来抓取网页。这是 Python 脚本的 sn-p:

html = driver.page_source

soup = soup(html, 'html.parser')
print(soup)
soup = soup(html, 'html.parser')
print(soup)

第一个print(soup) 返回解析后的html。第二个print(soup) 返回[]。这是为什么?一般来说,我对抓取和 Python 还是很陌生,因此非常感谢这里的任何指导。谢谢!

【问题讨论】:

    标签: python selenium selenium-webdriver beautifulsoup selenium-chromedriver


    【解决方案1】:

    在第一个表达式中,您将 soup 重新绑定到已解析的 BeautifulSoup 对象:

    soup = soup(html, 'html.parser')
    

    在打印之后,您现在调用这个重新绑定的对象 (soup);例如不是最好选择的变量名的情况?

    你的导入是什么,这个 soup() 构造函数来自哪里?
    如果您坚持调用构造函数/创建对象的正统方式 - 直接使用 BeautifulSoup(),它会更加简洁 - 并且不易出错:

    from bs4 import BeautifulSoup
    
    # your code to get some html
    
    soup = BeautifulSoup(html, 'html.parser')
    print(soup)
    soup = BeautifulSoup(html, 'html.parser')
    print(soup)
    

    【讨论】:

      【解决方案2】:

      因为你用一个名为“soup”的变量覆盖了你的 soup() 函数。

      试试这个:

      html = driver.page_source
      
      soup_ = soup(html, 'html.parser')
      print(soup_)
      soup_ = soup(html, 'html.parser')
      print(soup_)
      

      希望对你有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-06
        • 2014-03-06
        • 2011-07-21
        • 2012-12-13
        • 2011-09-24
        • 2018-07-10
        • 2021-10-31
        相关资源
        最近更新 更多