如何在CNN上获取主要标题?

时间:2019-07-07 07:20:45

标签: python web-scraping beautifulsoup

enter image description here

试图只抓住“大使称王不称职”,但我似乎无法降落在那个地区。我尝试拉“ h2”和类以及“强标签,但似乎找不到任何东西。下面的代码按原样保留了它,这是我唯一可以显示的东西。

soup = BeautifulSoup(data.text,'html.parser')
    for rows in soup.find_all('li'):
        for x in soup.findChildren('div'):
            print(x)

1 个答案:

答案 0 :(得分:2)

页面动态加载数据。如果您检查页面正在向哪些URL请求(例如,在Firefox Developer Tools中),您会发现数据位于不同的URL中。不幸的是,该URL(https://edition.cnn.com/data/ocs/section/index.html:intl_homepage1-zone-1/views/zones/common/zone-manager.izl)是动态构造的:

import requests
from bs4 import BeautifulSoup

url = 'https://edition.cnn.com/data/ocs/section/index.html:intl_homepage1-zone-1/views/zones/common/zone-manager.izl'
soup = BeautifulSoup(requests.get(url).text, 'lxml')
print(soup.h2.text)

打印:

UK ambassador calls Trump 'inept' and 'insecure'