首页 > 解决方案 > 无法通过python中的请求访问网页

问题描述

在与我的问题进行了一些讨论之后,在通过 selenium 自动化时无法使用 beautifulsoup 打印链接

我意识到主要问题在于请求无法提取的 URL。该页面的 URL 实际上是https://society6.com/discover但我使用 selenium 登录我的帐户,因此 URL 变为https://society6.com/society?show=2

但是,由于显示错误,我不能将第二个 URL 用于请求。我如何从这样的 URL 中删除信息。

标签: pythonseleniumselenium-webdriverweb-scrapingbeautifulsoup

解决方案


您需要先登录!

为此,您可以使用该bs4.BeautifulSoup库。

这是我使用的一个实现:

import requests
from bs4 import BeautifulSoup

BASE_URL = "https://society6.com/"


def log_in_and_get_session():
    """
    Get the session object with login details
    :return: requests.Session
    """    
    ss = requests.Session()
    ss.verify = False    # optinal for uncertifaied sites. 
    text = ss.get(f"{BASE_URL}login").text
    csrf_token = BeautifulSoup(text, "html.parser").input["value"]
    data = {"username": "your_username", "password": "your_password", "csrfmiddlewaretoken": csrf_token}
    # results = ss.post("{}login".format(BASE_URL), data=data)
    results = ss.post("{}login".format(BASE_URL), data=data)
    if results.ok:
        print("Login success", results.status_code)
        return ss
    else:
        print("Can't  login", results.status_code)

使用 'post' 方法登录...

希望这对你有帮助!

编辑

添加了函数的开头。


推荐阅读