簡體   English   中英

如何使用 Python 從需要登錄信息的網站下載文件?

[英]How to download file from website that requires login information using Python?

我正在嘗試使用 Python 從網站下載一些數據。 如果您只是復制並粘貼 url,除非您填寫登錄信息,否則它不會顯示任何內容。 我有登錄名和密碼,但是我應該如何將它們包含在 Python 中?

我目前的代碼是:

import urllib, urllib2, cookielib

username = my_user_name
password = my_pwd

link = 'www.google.com' # just for instance
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})

opener.open(link, login_data)
resp = opener.open(link,login_data)
print resp.read()

沒有錯誤彈出,但是 resp.read() 是一堆 CSS,它只有“你必須先登錄才能在這里閱讀新聞”這樣的消息。

那么如何找回登錄后的頁面呢?

剛剛注意到該網站需要 3 個條目:

Company: 

Username: 

Password:

我擁有所有這些,但是如何將所有三個都放在登錄變量中?

如果我在沒有登錄的情況下運行它,它會返回:

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

opener.open(dd)
resp = opener.open(dd)

print resp.read()

這是打印輸出:

<DIV id=header>
<DIV id=strapline><!-- login_display -->
<P><FONT color=#000000>All third party users of this website and/or data produced by the Baltic do so at their own risk. The Baltic owes no duty of care or any other obligation to any party other than the contractual obligations which it owes to its direct contractual partners. </FONT></P><IMG src="images/top-strap.gif"> <!-- template [strapline]--></DIV><!-- end strapline -->
<DIV id=memberNav>
<FORM class=members id=form1 name=form1 action=client_login/client_authorise.asp?action=login method=post onsubmits="return check()">

Usign scrapy 用於抓取該數據, Scrapy

然后你可以這樣做

class LoginSpider(Spider):
    name = 'example.com'
    start_urls = ['http://www.example.com/users/login.php']

    def parse(self, response):
        return [FormRequest.from_response(response,
                    formdata={'username': 'john', 'password': 'secret'},
                    callback=self.after_login)]

    def after_login(self, response):
        # check login succeed before going on
        if "authentication failed" in response.body:
            self.log("Login failed", level=log.ERROR)
            return

這段代碼應該可以工作,使用Python-Requests - 只需將...替換為實際域,當然還有登錄數據。

from requests import Session

s = Session() # this session will hold the cookies

# here we first login and get our session cookie
s.post("http://.../client_login/client_authorise.asp?action=login", {"companyName":"some_company", "password":"some_password", "username":"some_user", "status":""})

# now we're logged in and can request any page
resp = s.get("http://.../").text

print(resp)

嘗試在標題中使用另一個用戶代理。 看起來該站點具有某種類型的刮板檢測,您沒有提供用於檢查的 URL。 一些網站進行 javascript 測試以檢查請求是否看起來是自動化的,在這種情況下,請使用 playwright 或 selenium。

暫無
暫無

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

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