我一直在尝试编写一个脚本来检索我在 spoj See more 上接受的解决方案
我陷入了自动化登录过程的困境。我发现 Scrapy 很难理解。在多次查看文档和代码示例后,我对幕后发生的事情有了一个模糊的了解,这就是我现在所处的位置:
(我已经在需要的地方注释了代码)
import os
import os.path
import scrapy
import urllib.request
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from bs4 import BeautifulSoup
class LoginSpider(scrapy.Spider):
name = 'spoj'
start_urls = ['http://www.spoj.com/login']
outputFile = open('output.txt' , 'w')
def parse(self, response):
username = input('Enter username\n')
password = input('Enter password\n')
return scrapy.FormRequest.from_response(
response,
formdata={'username': username, 'password': password},
callback=self.after_login
)
def after_login(self, response):
# Even if I type in correct username and password it always leads to
# authentication faliure and the following if statement evaluates to true.
if str.encode('Authentication failed!') in response.body:
self.logger.error("Login failed")
print ('Incorrect credentials')
return
print('lol') # ofcourse this isn't printed
return scrapy.Request(url = "http://www.spoj.com/myaccount/" , callback = self.retrieve_codes )
# needless to say, the following function is never called
def retrieve_codes(self, response):
print('Hello testing!')
url = 'http://www.spoj.com/files/src/16731976/'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html , 'html.parser')
self.outputFile.write(str(soup.prettify()))
在文档中,我将其更改为if "authentication failed"in response.body:
if str.encode('Authentication failed!') in response.body:
原因是
- 我收到此错误
需要类似字节的对象而不是“str”
- 在 spoj 中输入错误的凭据时,会显示
Authentication failed!
,而不是authentication failed
。我们在这里需要精确。
请告诉我哪里做错了。我在网上没有找到任何详细讨论表单验证问题的好资源。看到后this code from docs我最初的问题是,
- 这是唯一的方法吗?
- 此方法适用于每个网站吗?因为我了解到这个过程的复杂性因站点而异。
- 我可以找到对背后发生的事情更具描述性的解释吗?
我也尝试过使用 robobrowser 但没有成功。 我有点期待像美丽的汤那样好的文档。
谢谢!
最佳答案
您使用了错误的 formdata
字段名称。您需要将 scrapy 文档中的示例代码调整到特定网站。目前,您使用用户名
和密码
作为formdata
字段。
如果您在登录时使用浏览器的开发人员工具,您可以看到通过 POST
发送的字段标记为 login_user
和 password
.
所以这应该很容易解决:-)
关于python - 使用Scrapy Python进行登录自动化和爬行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43924928/