首页 > 解决方案 > 如何让 Python3 网页抓取程序处理本地 cookie?

问题描述

我试图编写一个可以自动下载文件的程序(带有php链接)。但是,我现在有两个问题

首先,我的目标网站需要注册才能首次访问。然后,每次我点击下载链接时,它都会自动下载我想要的文件。看起来像是搜索了一些保存在我电脑上的 cookie 以确定我是谁。如何让我的 python 程序处理我的本地 cookie?如果是倍数?

其次,谁能给我一个关于如何处理php下载链接文件的示例代码?我想以特定名称将所有这些文件保存在特定位置。我应该如何在python3中做到这一点?

标签: phppythonweb-scrapingweb-crawlersession-cookies

解决方案


获取 cookie:

尝试:

import urllib.request
cookier = urllib.request.HTTPCookieProcessor()
# create the cookie handler
opener = urllib.request.build_opener(cookier)
urllib.request.install_opener(opener)

HTTPCookieProcessor返回cookielib.CookieJar包含这些 cookie 的对象。您可以遍历它以找到您想要的cookie。

for c in cookier.cookiejar: 
    if c.domain == '.stackoverflow.com': 
        # do something

阅读链接中的内容:

尝试:

url = 'YOUR_URL'
req = urllib.request.Request(url, headers=_headers) # where headers is the header setting you can find in your brwoser
f = urllib.request.urlopen(req)
contents = f.read().decode('utf-8')
# contents is the content inside your file
# You can add the code here to write contents to other file to save it

推荐阅读