使用请求和 BeautifulSoup 登录以抓取页面

时间:2021-06-18 07:56:56

标签: python authentication beautifulsoup python-requests session-cookies

我需要抓取一个需要登录才能访问的页面。

我尝试使用在 cUrl 中转换的保存登录信息登录,使用请求和 BeautifulSoup,但它不起作用。

我需要登录“https://www.seoprofiler.com/account/login” 然后抓取页面,如:'https://www.seoprofiler.com/lp/links?q=test.com'

这是我的代码:

from bs4 import BeautifulSoup 
import requests



cookies = {
    'csrftoken': 'token123',
    'seoprofilersession': 'session123',
}

headers = {
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
    'sec-ch-ua': '^\\^',
    'sec-ch-ua-mobile': '?0',
    'Upgrade-Insecure-Requests': '1',
    'Origin': 'https://www.seoprofiler.com',
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 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',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Referer': 'https://www.seoprofiler.com/account/login',
    'Accept-Language': 'en,en-US;q=0.9,it;q=0.8',
}

data = {
    'csrfmiddlewaretoken': 'token123',
    'username': 'email123@gmail.com',
    'password': 'pass123!',
    'button': ''
}



response = requests.post('https://www.seoprofiler.com/account/login',
                             headers=headers, cookies=cookies, data=data)


url = 'https://www.seoprofiler.com/lp/links?q=test.com'
response = requests.get(url, headers= headers, cookies=cookies)
soup = BeautifulSoup(response.content, 'html.parser')
soup.encode('utf-8')
print(soup.title)

我不会使用 selenium,因为我必须抓取大量数据,而且使用 selenium 需要很多时间。

我如何登录以抓取已登录的页面? 谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用 requests.Session!

经过反复试验,我能够使用以下脚本登录并获取项目页面:

import requests

session = requests.Session() # Create new session
session.get(
    "https://www.seoprofiler.com/account/login"
)  # set seoprofilersession and csrftoken cookies

session.post(
    "https://www.seoprofiler.com/account/login",
    data={
        "csrfmiddlewaretoken": session.cookies.get_dict()["csrftoken"],
        "username": "your_email",
        "password": "your_password",
    },
)  # login, sets needed cookies

# Now use this session to get all data you need!
resp = session.get(
    "https://www.seoprofiler.com/project/google.com-fa1b9c855721f3d5"
)  # get main page content

print(resp.status_code) # my output: 200

已编辑:

再检查一件事,似乎不需要检索 seoprofilersession 和 csrftoken cookie,您只需使用您的凭据调用登录帖子即可(无需 csrfmiddlewaretoken,然后使用您的会话)

答案 1 :(得分:0)

您如何知道必须传递给登录页面的 data 结构? 更可靠的解决方案使用 selenium 填充登录页面的 usernamepassword 字段,然后单击登录按钮。接下来,转到所需页面并抓取该页面。