代码之家  ›  专栏  ›  技术社区  ›  Ninja2k

scrapy可以根据id提交到输入吗?

  •  0
  • Ninja2k  · 技术社区  · 7 年前

    我有一个包含多个输入字段的内联网页,我需要scrapy使用网页“搜索产品”输入字段运行搜索,它的id为“searchbox”

    我已经能够使用scrapy和beautiful soup锁定正确的搜索框,但我不确定如何将该数据正确地传递回scrapys表单提交功能。

    在方法1中,我试图简单地将结果作为输入传递给scrapys formrequest.from_response函数,但它不起作用。

    方法1-使用scrapy查找数据

    #Search for products
    def parse(self, response):
    
        ##Let's try search using scrapy only
        sel = Selector(response)
        results = sel.xpath("//*[contains(@id, 'searchBox')]")
        for result in results:
            print (result.extract())   #Print out what scrapy found
        return scrapy.FormRequest.from_response(results, formdata = {'Item': 'Whirlpool Washing Machine'}) #formdata is the data we are sending
    

    方法2-使用beautiful soup查找数据

    #Search for products
    def parse(self, response):
    
        ##Let's try search using Beautiful Soup only
        soup = BeautifulSoup(response.text, 'html.parser')  
        product_search = []
        product_search.append(soup.find("input", id="searchBox")) 
        print(product_search) #Print what BS found
    
    0 回复  |  直到 7 年前
        1
  •  0
  •   vezunchik    7 年前

    关于Scrapy变体:

    1. 你应该 yield 请求,而不是 return .
    2. 在功能中 from_response 您应该使用表单选择器作为第一个参数。现在,您传递一些输入数据,据我从您的代码了解。

    尝试以下方法:

    yield scrapy.FormRequest.from_response(response.css('form'), formdata={'Item': 'Whirlpool Washing Machine'})
    

    只需修复此表达式中的窗体选择器。还要检查这个请求中还应该使用什么,可能是一些头文件、cookies等。