我正在尝试从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)
该页面上的数据是通过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 ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句