使用请求登录后,无法使用Selenium获取配置文件名称

2024-07-03 06:18:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python编写了一个脚本,以便在SO中只在我的概要文件中看到名称。问题是我想使用requests模块登录该站点,一旦登录,我希望使用Selenium获得配置文件名。底线是——当我获得概要文件URL时,我希望Selenium重用该URL来获取概要文件名。在

此工作解决方案使用请求

import requests
from bs4 import BeautifulSoup

url = "https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2f"

req = requests.get(url)
sauce = BeautifulSoup(req.text,"lxml")
fkey = sauce.select_one("[name='fkey']")['value']
payload = {
    'fkey': fkey,
    'ssrc': 'head',
    'email': my_username,
    'password': my_password,
    'oauth_version':'', 
    'oauth_server':'' 
    }
res = requests.post(url,data=payload)
soup = BeautifulSoup(res.text,"lxml")
item = soup.select_one("div[class^='gravatar-wrapper-']").get("title")
print(item)

我现在想做的是:

^{pr2}$

执行时遇到以下错误:

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unable to set cookie

如何通过重用从请求派生的profile url使用Selenium获取配置文件名称?


Tags: 文件import名称urlget文件名seleniumrequests
2条回答

使用Stack Exchange API可能比浏览站点更合适,但无论如何。。在

有几个问题:

  1. 你有时会遇到验证码挑战。

  2. 保留默认的requests标题会增加获得验证码的几率,因此请使用传统浏览器中的验证码覆盖它。

  3. 您需要使用requests.Session()来维护前两个请求的cookies。

  4. 在添加来自requests会话的cookies之前,您需要使用webdriver发出初始请求并清除所有创建的cookie。

考虑到这些因素,我可以让它与以下方面一起工作:

import requests
from bs4 import BeautifulSoup
from selenium import webdriver

url = "https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2f"

headers = {
    "User-Agent": (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
        "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36"
    )
}

s = requests.Session()

req = s.get(url, headers=headers)
payload = {
    "fkey": BeautifulSoup(req.text, "lxml").select_one("[name='fkey']")["value"],
    "email": "YOUR_EMAIL",
    "password": "YOUR_PASSWORD",
}

res = s.post(url, headers=headers, data=payload)

if "captcha" in res.url:
    raise ValueError("Encountered captcha")

driver = webdriver.Chrome()

try:
    driver.get(res.url)
    driver.delete_all_cookies()

    for cookie in s.cookies.items():
        driver.add_cookie({"name": cookie[0], "value": cookie[1]})

    driver.get(res.url)

    item = driver.find_element_by_css_selector("div[class^='gravatar-wrapper-']")
    print(item.get_attribute("title"))
finally:
    driver.quit()

你需要在cookie将对其有效的域中。在

在调用driver.add_cookie()之前,必须首先从该域导航到[任何]页。。。因此,在尝试添加cookie之前,再调用driver.get(url)。即使是一个错误页也足够了:

driver.get('https://stackoverflow.com/404')

例如。。。在

在代码中更改:

driver.add_cookie(cookie_item[0])
driver.get(res.url)

为此:

^{pr2}$

相关问题 更多 >