【问题标题】:Web Scraping: how to extract this kind of div tag?Web Scraping:如何提取这种 div 标签?
【发布时间】:2021-06-12 00:48:51
【问题描述】:

我在看一个标签:

.

当我写代码时,

message = soup.find("div", {"class": "text-msg-container"})

它没有给我。什么是 _ngcontent-vex-c62data-e2e-text-message-content 标签?我也需要包括它们吗?我应该如何编写它们以获得 div 标签?

【问题讨论】:

    标签: python selenium selenium-webdriver beautifulsoup


    【解决方案1】:

    您不能,因为当您发送 GET 请求以获取页面代码时,该 div 不存在。

    该页面是使用生成 SPA(单页应用程序)的 Angular 框架构建的,这意味着当您发送 GET 请求时,您无法从其中抓取数据,因为数据不存在. 数据由 Javascript 代码生成,需要先运行才能将所需数据添加到网页。

    您需要使用另一种方式,让 Javascript 代码先运行,然后尝试获取所需的数据。

    【讨论】:

    • 这个 div 似乎是动态创建的,但你怎么知道它是 Angular 的呢?问题中似乎没有足够的信息。
    • 我知道它使用的是来自 _ngcontent 的 Angular。通常 Angular 使用 ng 作为其组件的前缀。我建议您使用扩展程序向您展示网站使用的技术,例如 Wappalyzer 扩展程序。
    • 感谢您提供的信息!我很理解为什么它没有给我!
    【解决方案2】:

    如果您想查找课程text-msg-container,请尝试 Selenium。它可以轻松找到任何定位器。

    import unittest    
    from selenium import webdriver
        
        class PythonSearch(unittest.TestCase):
        
            def setUp(self):
                self.driver = webdriver.Firefox()
        
            def test_search(self):
                driver = self.driver
                driver.get("http://www.yoursite.com")
                elem = driver.find_element_by_css_selector(".text-msg-container")
        
            def tearDown(self):
                self.driver.close()
        
        if __name__ == "__main__":
            unittest.main()
    

    如果您正在测试 Chrome,请使用 driver = webdriver.Chrome('/path/to/chromedriver')。在这里查看更多信息https://chromedriver.chromium.org/getting-started。 Selenium 入门https://selenium-python.readthedocs.io/getting-started.html#simple-usage

    【讨论】:

    • 好的,我会试试selenium!谢谢!
    【解决方案3】:

    请试试这个

    message = soup.find("div", _class="text-msg-container")
    

    【讨论】:

    • 仍然给我,'没有'!
    【解决方案4】:

    我希望这有效

    from selenium import webdriver
    
    path = "C:/chromedriver.exe"    ### path to downloaded chromedriver on your 
                                    #pc change this directory or put the same location C:
    
    driver = webdriver.Chrome(path) ## your browser change it if you are not using chrome 
    driver.get("website link")
    
    out = driver.find_element_by_class_name("text-msg-container")
    print(out.text)
    

    【讨论】:

    • 好,我试试!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    相关资源
    最近更新 更多