【问题标题】:Can scrapy submit to an input based on id?scrapy 可以根据 id 提交输入吗?
【发布时间】:2019-07-31 10:07:09
【问题描述】:

我有一个包含多个输入字段的 Intranet 页面,我需要 Scrapy 使用网页“搜索产品”输入字段运行搜索,它的 id 为“searchBox”

我已经能够使用 Scrapy 和 Beautiful Soup 锁定正确的搜索框,但我不确定如何正确地将这些数据传递回 Scrapys 表单提交功能。

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

方法一 - 使用 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

方法二——用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

【问题讨论】:

    标签: python beautifulsoup scrapy


    【解决方案1】:

    关于scrapy变种:

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

    尝试类似:

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

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

    【讨论】:

    • 我认为输入是由 JavaScript 动态生成的,因为当我在 Chrome 中刷新页面时,它在浏览器中具有不同的输入 name=
    • 只有您可以看到,因为我们无权访问您的 Intranet 页面。我们只能建议可能出错的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 2020-11-30
    • 1970-01-01
    相关资源
    最近更新 更多