[英]Error: raise ValueError(“No element found in %s” % response) occur when try to login with scrappy
我想從我大學的bbs中抓取一些信息。 這是地址: http : //bbs.byr.cn下面是我的蜘蛛的代碼:
from lxml import etree
import scrapy
try:
from scrapy.spiders import Spider
except:
from scrapy.spiders import BaseSpider as Spider
from scrapy.http import Request
class ITJobInfoSpider(scrapy.Spider):
name = "ITJobInfoSpider"
start_urls = ["http://bbs.byr.cn/#!login"]
def parse(self,response):
return scrapy.FormRequest.from_response(
response,
formdata={'method':'post','id': 'username', 'passwd':'password'},
formxpath='//form[@action="/login"]',
callback=self.after_login
)
def after_login(self,response):
print "######response body: " + response.body +"\n"
if "authentication failed" in response.body:
print "#######Login failed#########\n"
return
但是,使用此代碼,我經常會收到錯誤:引發ValueError(“在%s中找不到元素”%響應)
我發現當scrapy嘗試解析url的HTML代碼時會發生此錯誤: http ://bbs.byr.cn,scrappy用lxml解析頁面。 下面是代碼
root = LxmlDocument(response, lxml.html.HTMLParser)
forms = root.xpath('//form')
if not forms:
raise ValueError("No <form> element found in %s" % response)
所以我用代碼查看代碼: print etree.tostring(root)
並發現HTML元素: </form>
被解析為</form>
難怪代碼forms = root.xpath('//form')
將返回一個空表單列表。
但我不知道為什么會這樣,也許是HTML代碼編碼? (HTML代碼使用GBK編碼,而不是UTF8。)感謝任何可以幫助我的人嗎? 順便說一句,如果有人想要針對網站編寫代碼,我可以給你一個測試帳戶,請在評論中留下我的電子郵件地址。
非常感謝,伙計們!
似乎有一些JavaScript重定向發生。
在這種情況下,使用Splash會有點矯枉過正。 只需將/index
附加到起始URL: http://bbs.byr.cn → http://bbs.byr.cn/index
: http://bbs.byr.cn → http://bbs.byr.cn/index
: http://bbs.byr.cn → http://bbs.byr.cn/index
這將是完整的工作蜘蛛:
from scrapy import Spider
from scrapy.http import FormRequest
class ByrSpider(Spider):
name = 'byr'
start_urls = ['http://bbs.byr.cn/index']
def parse(self, response):
return FormRequest.from_response(
response,
formdata={'method':'post','id': 'username', 'passwd':'password'},
formxpath='//form[@action="/login"]',
callback=self.after_login)
def after_login(self, response):
self.logger.debug(response.text)
if 'authentication failed' in response.text:
self.logger.debug('Login failed')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.