BeautifulSoup网页抓取,没有结果

时间:2020-10-05 16:57:22

标签: python beautifulsoup web-crawler

我正在尝试从https://hk.appledaily.com/search/apple抓取新闻信息。 而且我需要从div class="flex-feature"获取新闻内容,但它只会返回[]。希望任何人都能帮忙,谢谢!

from bs4 import BeautifulSoup
import requests


page = requests.get("https://hk.appledaily.com/search/apple")

soup = BeautifulSoup(page.content, 'lxml')

results = soup.find_all('div', class_ = "flex-feature")


print(results)

2 个答案:

答案 0 :(得分:1)

如果在浏览器中查看页面源,您会发现flex-feature在HTML中不存在。这是服务器在呈现JavaScript和所有动态内容之前最初发送回的HTML。这也是requests.get会给您([])的HTML。

要访问这些元素,您可能希望使用诸如Selenium之类的方法,使您可以自动执行浏览器并呈现动态加载页面的JavaScript。查看我对类似问题here的回答,以获取一些见解!

其他资源

答案 1 :(得分:1)

该页面上的数据是通过js动态获取和呈现的。因此,除非您评估javascript,否则将无法获取数据。

一种删除数据的方法是使用无头浏览器。
这是一个使用pyppeteer的示例。

import asyncio
from pyppeteer import launch

# https://pypi.org/project/pyppeteer/

URL = 'https://hk.appledaily.com/search/apple'

async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.goto(URL)

    await page.waitForSelector(".flex-feature")

    elements = await page.querySelectorAll('.flex-feature')
    
    for el in elements:
        text = await page.evaluate('(el) => el.textContent', el)
        print(text)


    await browser.close()

asyncio.get_event_loop().run_until_complete(main())

输出:

3小時前特朗普確診 不斷更新 特朗普新聞秘書及多名白宮職員確診 「白宮群組」持續擴大特朗普確診 不斷更新

 ... REDUCTED ...