因此,我试图从Gasbuddy.com上删除一些汽车信息,但是我在使用这些易破解的代码时遇到了一些麻烦。
这是我到目前为止所拥有的,请让我知道我做错了什么:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.loader import XPathItemLoader
from scrapy.http import Request
from scrapy.http import FormRequest
class gasBuddy(BaseSpider):
name = "gasBuddy"
allowed_domains = ["http://www.gasbuddy.com"]
start_urls = [
"http://www.gasbuddy.com/Trip_Calculator.aspx",
]
def parse(self, response):
hxs = HtmlXPathSelector(response)
#for years in hxs.select('//select[@id="ddlYear"]/option/text()'):
#print years
FormRequest(url="http://www.gasbuddy.com/Trip_Calculator.aspx",
formdata={'Year': '%s'%("2011")},
callback=self.make('2011'))
def make (years, self, response):
#this is where we loop through all of the car makes and send the response to modle
hxs = HtmlXPathSelector(response)
for makes in hxs.select('//select[@id="ddlMake"]/option/text()').extract()
FormRequest(url="http://www.gasbuddy.com/Trip_Calculator.aspx",
formdata={'Year': '%s', 'Make': '%s'%(years, makes)},
callback=self.model(years, makes))
def model (years, makes, self, response):
#this is where we loop through all of the car modles and get all of the data assoceated with it.
hxs = HtmlXPathSelector(response)
for models in hxs.select('//select[@id="ddlModel"]/option/text()')
FormRequest(url="http://www.gasbuddy.com/Trip_Calculator.aspx",
formdata={'Year': '%s', 'Make': '%s', 'Model': '%s'%(years, makes, models)},
callback=self.model(years, makes))
print hxs.select('//td[@id="tdCityMpg"]/text()')
最佳答案
该答案仅涵盖使用附加参数调用回调的方法,而不能解决具体站点的动态表单问题。
要将其他参数传递给回调,可以使用标准Python库中的 functools.partial
。
没有Scrapy的简化示例:
import functools
def func(self, response):
print self, response
def func_with_param(self, response, param):
print self, response, param
def caller(callback):
callback('self', 'response')
caller(func)
caller(functools.partial(func_with_param, param='param'))
make
和model
函数(self
始终是第一个参数):def make (self, response, years):
...
def model (self, response, years, makes):
...
import functools
...
def parse(self, response):
...
return FormRequest(url="http://www.gasbuddy.com/Trip_Calculator.aspx",
formdata={'Year': '%s'%("2011")},
callback=functools.partial(self.make, years='2011'))
meta
使用 FormRequest
参数def parse(self, response):
...
return FormRequest(url="http://www.gasbuddy.com/Trip_Calculator.aspx",
formdata={'Year': '%s'%("2011")},
meta={'years':'2011'},
callback=self.make)
def make (self, response):
years = response.meta['years']
...
models
类似。FormRequest
,仅创建而不使用。您应该返回它们(例如在我的parse
示例中)或在for循环中将它们yield
:for something in hxs.select(...).extract():
yield FormRequest(...)
https://stackoverflow.com/questions/8984816/