簡體   English   中英

Python和SeleniumRequests獲得請求標頭

[英]Python and seleniumrequests getting request headers

我需要從特定請求中獲取Cookie。 問題是它是在我眼外生成的,我需要使用Selenium來模擬瀏覽器打開,以便我自己生成它。 第二個問題是我無法訪問請求cookie。 我需要的cookie在請求中,而不是響應中。

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

binary = FirefoxBinary('/usr/bin/firefox')
driver = webdriver.Firefox(firefox_binary=binary)
driver.get('http://www.princess.com/find/searchResults.do')
driver.find_elements_by_xpath('//*[@id="LSV010"]/div[3]/div[1]/div[1]/button')[0].click()

此代碼塊打開頁面,並在第二個結果上,單擊“查看所有日期和價格”鏈接。 Cookie是通過瀏覽器發送到那里的,而不是作為響應發送的。 我需要拿起那塊餅干。 其他圖書館也可以的話。 如果您手動轉到頁面,這是我需要的東西: 在此處輸入圖片說明 我選擇了請求和我需要的Cookie,並顯示它在請求中而不是響應中。 這有可能實現嗎?

我發現這是怎么做的。 使用selenium庫,我確實設法使它工作:

def fix_header():
    browser = webdriver.Firefox(executable_path='geckodriver.exe', firefox_profile=profile)
    browser.get('https://www.princess.com/find/searchResults.do')
    browser.find_element_by_xpath(
        "//*[@class='expand-table view-all-link util-link plain-text-btn gotham-bold']")
    WebDriverWait(browser, 60).until(EC.visibility_of_any_elements_located(
        (By.XPATH, "//*[@class='expand-table view-all-link util-link plain-text-btn gotham-bold']")))
    try:
        browser.find_element_by_xpath(
            "//*[@class='expand-table view-all-link util-link plain-text-btn gotham-bold']").click()
    except Exception:
        browser.find_element_by_class_name('mfp-close').click()
        browser.find_element_by_xpath(
            "//*[@class='expand-table view-all-link util-link plain-text-btn gotham-bold']").click()

    cookies = browser.get_cookies()
    browser.close()
    chrome_cookie = ''
    for c in cookies:
        chrome_cookie += c['name']
        chrome_cookie += '='
        chrome_cookie += c['value']
        chrome_cookie += "; "
    return chrome_cookie[:-2]

Selenium實際上轉到該頁面,並用瀏覽器“單擊”我需要的url ,並獲取所需的cookie。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM