使用nodeJS,我希望能够使用用户凭据登录彭博社,然后以登录用户身份进行抓取。最好不要使用 Selenium,因为根据我的经验,Selenium 很慢。
有人以前做过这个或知道建议的替代方法吗?
知道如何执行此操作而无需登录我需要抓取的每篇文章也非常有用。
我目前能够抓取非付费内容,而无需通过 Axios.get 登录并指定用户代理 + Cheerio(用于简单的 .class 选择器)。
我使用这篇文章https://www.bloomberg.com/news/articles/2023-06-28/doordash-introduces-hourly-minimum-rate-option-for-dashers。如果不登录,您会看到 2 个段落,但如果登录并订阅 Bloomberg,则会看到 7 个段落。
但是,我无法使用 https://www.bloomberg.com/account/signin 向 Bloomberg 提交 POST 请求。这是我尝试这样做的方法:
import axios from 'axios';
import { CookieJar } from 'tough-cookie';
import { wrapper } from 'axios-cookiejar-support';
const cookieJar = new CookieJar();
const client = wrapper(axios.create({ cookieJar }));
const loginData = {
username: 'my_username',
password: 'my_password'
};
// login
client.post('https://www.bloomberg.com/account/signin', loginData, {
jar: cookieJar,
withCredentials: true
}).then((response) => {
console.log(response.data);
}).catch((error) => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
console.log("path1")
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in Node.js
console.log(error.request);
console.log("path2")
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
console.log("path3")
}
console.log(error.config);
console.log("path4");
});
我还尝试查看页面将 POST 请求发送到哪个 URL,但在向页面提交凭据时找不到任何 POST 请求(只有 GET 请求)。为什么没有发送 POST 请求?即使它是一个单页应用程序,我觉得它仍然应该发送某种 POST 来验证登录。
我收到 405 错误代码(path1),这意味着 URL 不支持我发出的请求方法。(POST?)还收到 error.config(path4),但我认为这是 405 错误代码的次要原因。
import requests
import pandas as pd
from datetime import timedelta
from selenium import webdriver
from bs4 import BeautifulSoup
from requests_html import HTMLSession
from dateutil.parser import parse as parse_datetime
session = HTMLSession()
url = "https://www.bloomberg.com/news/articles/2024-05-08/stock-market-today-dow-s-p-live-updates"
cookie_str= "INSERT YOUR COOKIE STR HERE"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Referer': 'https://www.google.com/',
'Connection': 'keep-alive',
'Cookie': cookie_str
}
r = session.get(url, headers=headers)
soup = BeautifulSoup(r.html.html, 'html.parser')
它无需您在不传递您的用户/密码的情况下进行处理即可工作。它与包 requests_html 一起解析 javascript。但 BBG 在机器人检查方面的速度是出了名的快。