无法使用BeautifulSoup访问HTML子标记

2024-09-27 02:17:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试访问CNN网站上的文章元数据。他们的“头条新闻”部分下面有一个标签,开头如下:

<section class="zn zn-homepage1-zone-1....

在该部分下面,每一篇文章都位于标签的内部,如下所示:

<article class="cd cd--card cd--article....

在类似的网站上,我可以通过以下方式访问“热门新闻”报道:

cnnUrl = "https://www.cnn.com"
cnnSoup = BeautifulSoup(requests.get(cnnUrl, headers=headers).content, "html.parser")

homepageZone1 = '[class*="zn zn-homepage1-zone-1"]'

for item in cnnSoup.select(homepageZone1):

…for循环将允许我访问子标记,在那里我可以收集所需的数据。一旦我有了item,我通常可以为CNN的头条新闻标题文本做类似的事情(这种格式不时变化):

headline = item.find('h2').get_text()

其中headline将是(截至目前):

A Petri Dish For the Country

然而,在本例中,我得到了homepageZone1标记的None类型。我尝试退出到homepageZone1的父div:

cnnEverything = '[class*="pg-no-rail pg-wrapper"]'

for item in cnnSoup.select(cnnEverything):

Item这里为我提供了以下子标记,但这些标记实际上都没有我可以访问的子标记:

<div class="pg-no-rail pg-wrapper"><div class="pg__background__image_wrapper"></div><div class="l-container"></div><section class="zn--idx-0 zn-empty"> </section><section class="zn--idx-1 zn-empty"> </section><section class="zn--idx-2 zn-empty"> </section><section class="zn--idx-3 zn-empty"> </section><section class="zn--idx-4 zn-empty"> </section><section class="zn--idx-5 zn-empty"> </section><section class="zn--idx-6 zn-empty"> </section><section class="zn--idx-7 zn-empty"> </section><section class="zn--idx-8 zn-empty"> </section><section class="zn--idx-9 zn-empty"> </section><section class="zn--idx-10 zn-empty"> </section><div class="ad ad--epic ad--all t-dark"><div class="ad-ad_bnr_btf_02 ad-refresh-adbody" data-ad-id="ad_bnr_btf_02" id="ad_bnr_btf_02"></div></div></div>

我错过了什么


Tags: 标记divforcdsectionitemwrapperad
1条回答
网友
1楼 · 发布于 2024-09-27 02:17:57

我认为您需要的HTML是在一个单独的请求中请求的,然后使用Javascript将其添加到主HTML中(这就是为什么您没有看到它)

下面显示了如何从返回的JSON中的HTML请求国际版本:

from bs4 import BeautifulSoup
import requests

# International version
r = requests.get("https://edition.cnn.com/data/ocs/section/index.html:intl_homepage1-zone-1/views/zones/common/zone-manager.izl")
json_data = r.json()
html = json_data['html'].replace(r'\"', '"')
cnnSoup = BeautifulSoup(html, 'html.parser')

for heading in cnnSoup.find_all(['h2', 'h3']):
    print(heading.text)

给你以下标题:

Kandahar falls to Taliban
Militants take control of Afghanistan's second-largest city during an unrelenting sweep of the country, weeks before US troops are due to complete withdrawal
LIVE: UK defense chief worried about potential return of al Qaeda
Video allegedly shows Taliban celebrating after Kandahar gain
Afghanistan's quick unraveling threatens to stain Biden's legacy
...

URL是在加载页面时通过查看浏览器发出的请求找到的

相关问题 更多 >

    热门问题