python - 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```
解决方案
以为我也可以发布我的涂鸦:
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?
推荐阅读
- postgresql - pq:剩余的连接槽保留给非复制超级用户和 rds_superuser 连接
- android - 我无法连接到真实设备的 ionic 3G 应用程序
- python - 如何将我的 pip 下载从 anaconda3 目录切换到 PyCharm?
- python - 如何使用 lambda 按字典中元组的值排序?
- angularjs - $window.open 带有上下文/标题
- c# - 可空的
作为参数 - python - Pandas .sort_values 未按预期排序
- swift - 如何将具有关系的 NSManagedObject 转换为 Swift 类?
- java - 如何遍历 MethodCall 对象以获取参数
- spring-mvc - 在spring mvc的@modelattribute中添加可选参数