python-2.7 - 如果我们有使用 python scrapy 的凭据,如何抓取已登录的网页?
问题描述
只想知道如何将请求与登录凭据一起发送到登录页面以获取数据。
解决方案
网站通常通过元素提供预填充的表单字段,例如会话相关数据或身份验证令牌(用于登录页面)。抓取时,您会希望自动预填充这些字段,并且只覆盖其中的几个,例如用户名和密码。您可以为此作业使用 FormRequest.from_response() 方法。这是一个使用它的示例蜘蛛:import scrapy
def authentication_failed(response):
# TODO: Check the contents of the response and return True if it failed
# or False if it succeeded.
pass
class LoginSpider(scrapy.Spider):
name = 'example.com'
start_urls = ['http://www.example.com/users/login.php']
def parse(self, response):
return scrapy.FormRequest.from_response(
response,
formdata={'username': 'john', 'password': 'secret'},
callback=self.after_login
)
def after_login(self, response):
if authentication_failed(response):
self.logger.error("Login failed")
return
# continue scraping with authenticated session...
推荐阅读
- python - 使用 cv2.imwrite() 保存 GRAYSCALE .png 图像不起作用
- ruby-on-rails - 使用 Ruby on Rails 运行 Rufus-Scheduler
- mysql - 在 wpdb select 中使用双引号和单引号
- ssrs-2008 - ssrs 选择下拉值作为字段名称
- javascript - nuxtjs/auth:使用 Auth0 权限数组作为 scopeKey
- sql - 使用分析或其他函数从现有列中派生新列值的 Oracle SQL 操作?我已经描述了想要的结果
- python - 无法使用 Python 和 BeautifulSoup 解析网站的 html
- javascript - API 调用失败并出现 401
- r - 将日期从字符转换为日期格式,可用于 R 中的时间序列分析
- apple-music - 我可以从 Apple MusicKit 获取用户的显示名称吗?