首页 > 解决方案 > Beautiful Soup 没有得到完整的 div

问题描述

BeautifulSoup 做了一些奇怪的事情,我不知道为什么。

import requests
from bs4 import BeautifulSoup

url = "nsfw"
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
cards = soup.find_all("div", {"class": "card-body"})
cards.pop(0)
cards.pop(0)
cards.pop(0)  # i really like to pop
texte = []
print(soup)
for i, card in enumerate(cards):
    texte.append(card.text)
    if i == len(cards)-1:
        print(card)

现在我期望它做的是获取 div 并将 div 的文本放入数组中。它确实有效。对于 9 个 div 中的前 8 个。第 9 个 div 被极度缩短。打印结果:

<div class="card-body" id="card_Part_9"><p class="storytext"><span class="brk2_firstwords">“Door’s open,” Brendan shouted.</span></p>
    <p class="storytext">Jeffrey</p></div>    

但在网站本身上,它并没有就此结束。这是截图:https ://i.imgur.com/CmvYzfJ.png

为什么会这样?我能做些什么来防止这种情况发生?我已经尝试更改解析器,但这不会改变结果。该网站不使用 Javascript 加载内容。

使用浏览器打开时的结构:https ://pastebin.com/N2bPYFBD

但是当我打印(汤)时,我得到:

<p class="storytext">Jeffrey</p></div></div></div></div></div></div></div></body></html> entered the apartment```

标签: pythonpython-3.xbeautifulsouppython-requests

解决方案


以为我也可以发布我的涂鸦:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('six-pack-thingy')
elems = driver.find_elements_by_class_name('card-body')

texte = [t.text for t in elems[3:]]

You will have to get some webdriver to run selenium, though. Are you familiar with that?


推荐阅读