我是个新手,我正在一个使用cookies的网络中使用scrapy,这对我来说是一个问题,因为我可以在没有cookies的网络上获取数据,但在有cookies的网络上获取数据对我来说很困难。
我有这个代码结构
class mySpider(BaseSpider):
name='data'
allowed_domains =[]
start_urls =["http://...."]
def parse(self, response):
sel = HtmlXPathSelector(response)
items = sel.xpath('//*[@id=..............')
vlrs =[]
for item in items:
myItem['img'] = item.xpath('....').extract()
yield myItem
这很好,我可以使用这个代码结构在没有cookie的情况下获得很好的数据
我发现它是因为我可以在这个 url 中使用 cookie,但我不明白应该将此代码放在哪里,然后才能使用 xpath 获取数据
我正在测试这段代码
request_with_cookies = Request(url="http://...",cookies={'country': 'UY'})
但我不知道我可以工作或把这段代码放在哪里,
我将此代码放入函数解析中,以获取数据
def parse(self, response):
request_with_cookies = Request(url="http://.....",cookies={'country':'UY'})
sel = HtmlXPathSelector(request_with_cookies)
print request_with_cookies
我尝试将 XPath 与带有 cookies 的新 url 一起使用,以便稍后打印这个新的数据抓取
我认为这就像使用没有 cookie 的 url
但是当我运行这个时,我遇到了一个错误,因为“Request”对象没有属性“body_as_unicode”
处理这些cookies的正确方法是什么,我有点迷失了
非常感谢。
你们非常接近!
parse() 方法的约定是:yield
s(或返回一个可迭代对象)Item
s, Request
s,或两者的混合。就你而言,你所要做的就是
yield request_with_cookies
并且您的 parse() 方法将再次运行Response
使用这些 cookie 请求该 URL 时生成的对象。
http://doc.scrapy.org/en/latest/topics/spiders.html?highlight=parse#scrapy.spider.Spider.parse http://doc.scrapy.org/en/latest/topics/spiders.html?highlight=parse#scrapy.spider.Spider.parse
http://doc.scrapy.org/en/latest/topics/request-response.html http://doc.scrapy.org/en/latest/topics/request-response.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)