python - 无限加载从新闻网站上抓取头条新闻

标签 python selenium-webdriver web-scraping

我想从这个网站上抓取头条新闻:https://www.marketwatch.com/latest-news?mod=top_nav
我需要加载较早的新闻,因此需要单击蓝色按钮“查看更多”。
我创建了这段代码,但没有用:

from bs4 import BeautifulSoup
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
u = 'https://www.marketwatch.com/latest-news?mod=top_nav' #US Business


driver = webdriver.Chrome(executable_path=r"C:/chromedriver.exe")
driver.maximize_window()
driver.get(u)
time.sleep(10)
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CLASS_NAME,'close-btn'))).click()
time.sleep(10)

driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
for i in range(3):
        element =WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'component.component--module.more-headlines div.group.group--buttons.cover > a.btn.btn--secondary.js--more-headlines)))
        driver.execute_script("arguments[0].scrollIntoView();", element)
        element.click()
        time.sleep(5)
        driver.execute_script("arguments[0].scrollIntoView();", element)

        print(f'click {i} done')
soup = BeautifulSoup(driver.page_source, 'html.parser')

driver.quit()
它返回此错误:
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

最佳答案

这样的事情会更可靠:

for i in range(3):
  driver.execute_script('''
    document.querySelector('a.js--more-headlines').click()
  ''')
  time.sleep(1)
请注意,当您从 javascript 中单击时,您不必滚动到 View 中

关于python - 无限加载从新闻网站上抓取头条新闻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65104175/

相关文章:

Python,如何清空文件中的特定行

python - 当属性匹配时,如何使用 Python 序列化 Avro 中的联合字段

python - 对具有更高优先级正数的绝对值的整数列表进行排序

java - 从终端执行 java 项目 jar 时出现错误

java - 我可以同时在不同端口上运行selenium服务器吗?

java - 在 Perl 中使用 java 对象

python - 使用网络抓取工具时,如何确保抓取第一页后,它会抓取第二页?

python mechanize - 无法提交登录表单

python - 模拟将 UUID 编码为 Base64

python - 无法从网页中抓取不同项目的标题