python - 如何将嵌套在 div 下的所有 div 抓取到列表中?

标签 python selenium selenium-webdriver web-scraping beautifulsoup

我目前正在使用 Selenium 和 BeautifulSoup 开发网络爬虫。我觉得我遇到的问题更多是由于我缺乏 Python 经验而不是由于使用库的经验。我的问题归结为,有一些没有类的 div 嵌套在带有我想要抓取到列表中的类的 div 下。我不完全确定如何运行这些嵌套的 div 并将所有信息放入列表中。我相信我的问题的一部分是由于我在 Python 中使用嵌套 for 循环的经验不足,因为我相信当前的 for 循环会导致无限循环。让我知道你的想法。谢谢!

from selenium import webdriver
from bs4 import BeautifulSoup
import time
import os

driver = webdriver.Firefox(executable_path="/Users/myuser/Documents/geckodriverfolder/geckodriver")

driver.get('https://rotogrinders.com/projected-stats?site=draftkings&sport=nba')

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

html = driver.page_source

soup = BeautifulSoup(html, 'lxml')

salary_opp = []
for test in soup.find_all('div', class_='rgt-col'):
  for test2 in soup.find_all('div'):
    draft_kings = test2.text
    salary_opp.append(draft_kings)

print(salary_opp)

这是我在 for 循环之前所拥有的,但它只将嵌套在单数 div 下的第一个 div 放入列表中:

for test in soup.find_all('div', class_='rgt-col'):
  draft_kings = test.div.text
  salary_opp.append(draft_kings)

最佳答案

如果你想获取没有类的标签,即<div>...</div> ,您可以使用class_=None .

for test in soup.find_all('div', class_='rgt-col'):
    for test2 in test.find_all('div', class_=None):
        draft_kings = test2.text
        salary_opp.append(draft_kings)

我没有检查循环背后的逻辑,而是使用 test.find_all('div', class_=None)会回答你的问题。另请注意,我更改了第二个 forsoup.find...循环至test.find... .

关于python - 如何将嵌套在 div 下的所有 div 抓取到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48538436/

相关文章:

selenium-webdriver - 为什么我的 Nightwatch 测试不能使用 selenium?

java - 指定ChromeDriver运行的端口

javascript - Selenium 网络驱动程序 : Can't access element containing onclick and text attributes

重启后 Raspberry Pi 上的 Python 虚拟环境错误

python - python 中的 Zip 不适用于列表

java - testng - 获取包含失败测试的类的名称

python - 使用 Tor 和 Selenium 获得新的身份。出现错误 "IncorrectSocketType: unable to use the control socket"

.net - .NET 中用于编写验收测试的维护最多的最新框架是什么?

python - 将数组的 numpy 数组转换为一个完整的 numpy 数组

python - 名称 exit 未在 python 中定义