How to write method to csv not just string? Ruby c

2019-09-20 06:21发布

问题:

I need to put the text content from an html element to a csv file. With the ruby csv gem, it seems that the primary write method for wrapped Strings and IOs only converts a string even if an object is specified.

For example:

 Searchresults = puts browser.divs(class: 'results_row').map(&:text)
 csv << %w(Searchresults)

returns only "searchresults" in the csv file.

It seems like there should be a way to specify the text from the div element to be put and not just a literal string.

Edit:

Okay arieljuod and spickermann were right. Now I am getting text content from the div element output to the csv, but not all of it like when I output to the console. The div element "results_row" has two a elements with text content. It also has a child div "results_subrow" with a paragraph of text content that is not getting written to the csv. HTML:

<div class="bodytag" style="padding-bottom:30px; overflow:visible"> 
<h2>Search Results for "serialnum3"</h2>
<div id="results_banner">
    Products
    <span>Showing 1 to 2 of 2 results</span>
</div>
<div class="pg_dir"></div>
<div class="results_row">
    <a href="/products/fuji/" title="Fuji, Inc.">FUJI</a>
    <a href="/products/fuji/50mm lens/" title="Fuji, Inc.">50mm lens</a>
    <div class="results_subrow">
        <p>more product info</p>
    </div>
</div>
<div class="results_row">
    <a href="/products/fuji/" title="Fuji, Inc. 2">FUJI</a>
    <a href="/products/fuji/50mm lens/" title="Fuji, Inc.">50mm lens</a>
    <div class="results_subrow">
        <p>more product info 2</p>  
    </div>
</div>
<div class="pg_dir"></div>  

My code:

 search_results = browser.divs(class: 'results_row').map(&:text)
 csv << search_results

I'm thinking that including the child div "results_subrow" in the locator will find what I am missing. Like:

search_results = browser.divs(class: 'results_row', 'results_subrow').map(&:text)
 csv << search_results

回答1:

%w[Searchresults] creates an array containing the word Searchresults. You probably want something like this:

# assign the array returned from `map` to the `search_results` variable
search_results = browser.divs(class: 'results_row').map(&:text)

# output the `search_results`. Note that the return value of `puts` is `nil`
# therefore something like `Searchresults = puts browser...` doesn't work
puts search_results

# append `search_results` to your csv 
csv << search_results