【问题标题】:How do you take the days article names on the website CNBC.com/business and put them in a list with python selenium chromedriver?你如何在网站 CNBC.com/business 上获取文章名称并使用 python selenium chromedriver 将它们放入列表中?
【发布时间】:2021-09-26 21:29:56
【问题描述】:

这是我到目前为止的代码。我的下一步是从网站上获取正确的元素,即。最新文章的名称并将它们放在一个列表中。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

PATH = "C:\webdrivers"
driver = webdriver.Chrome()

driver.get("https://www.cnbc.com/business/")

【问题讨论】:

  • 同时添加您尝试提取新闻的代码。
  • 我的下一步是从网站上获取正确的元素,即。最新文章的名称并将它们放入列表中。 - 我们需要查看代码。

标签: python selenium selenium-webdriver web-scraping htmlelements


【解决方案1】:

这是你应该做的:

from selenium import webdriver
from selenium.webdriver import ActionChains

PATH = "/Users/Samuel/PycharmProjects/MoneyMachine/drivers/chromedriver"
driver = webdriver.Chrome(PATH)
driver.get("https://www.cnbc.com/business/")
action = ActionChains(driver)

list = []

for i in range(2):
    element = driver.find_element_by_xpath(f"/html/body/div[2]/div/div[1]/div[3]/div/div/div/div[3]/div[1]/div[1]/section/div/div[1]/div[{i+1}]/div/div/div/div[1]/div/a/div").text
    list.append(element)

for i in range(3):
    element = driver.find_element_by_xpath(f"/html/body/div[2]/div/div[1]/div[3]/div/div/div/div[3]/div[1]/div[1]/section/div/div[2]/div[{i+1}]/div/div/div/div[1]/div/a/div").text
    list.append(element)

driver.close()

print(list)

driver.find_element_by_xpath("XPATH") 为您找到一个元素。要知道应该在引号中添加什么,请右键单击所需的元素,然后选择检查。然后,当您将鼠标悬停在检查窗口中的元素上时,右键单击并按复制完整 xpath。

我认为您应该为此类项目查看 BeautifulSoup (BS4),认为这对您的情况会更好。 BS4 更加用户友好。 以下是您应该在此项目中使用 BS4 的更多原因:

" 带宽和运行脚本的时间。使用 Selenium 意味着获取在浏览器中访问页面时通常会获取的所有资源 - 样式表、脚本、图像等。这可能是不必要的。 稳定性和易于错误恢复。根据我的经验,Selenium 可能有点脆弱——即使是使用 PhantomJS——创建架构来杀死挂起的 Selenium 实例并创建一个新实例比在使用请求时设置简单的异常重试逻辑更令人恼火。 潜在地,CPU 和内存使用 - 取决于您正在爬行的站点,以及您尝试并行运行的蜘蛛线程的数量,可以想象 DOM 布局逻辑或 JavaScript 执行可能会变得非常昂贵。 " 来自-Selenium versus BeautifulSoup for web scraping

【讨论】:

  • 你如何找到最近用 Beautiful Soup 发布的文章?
猜你喜欢
  • 2017-02-19
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
相关资源
最近更新 更多