在同一行上打印两个语句。

huangapple go评论73阅读模式
英文:

Printing 2 statements on the same line

问题

我已经成功制作了一个爬虫,可以爬取 eBay 上 iPhone 部分的所有 109 个页面。

问题是我需要将它们打印在同一行上。目前的情况是这样的在同一行上打印两个语句。

package main

import (
    "fmt"
    "github.com/gocolly/colly"
)

func main() {
    c := colly.NewCollector(colly.UserAgent("Mozilla/5.0 (X11; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0"))

    c.OnHTML(".s-item__title", func(element *colly.HTMLElement) {
        element.ChildAttr("heading", "role")
        fmt.Println(element.Text)
    })

    c.OnHTML(".s-item__price", func(element *colly.HTMLElement) {
        fmt.Println(element.Text)
    })

    c.Visit("https://www.ebay.com/sch/i.html?_from=R40&_nkw=iPhone&_sacat=0&_pgn=1")
}

甚至无法在这些信息之间进行导航。有人能告诉我如何在同一行上获取标题和价格吗?

我考虑过重命名元素,但没有成功。

我可以使用 printf 或 println,但它们只会将所有内容一起打印出来。

英文:

I've successfully made a scraper that scrapes all 109 pages of the iPhone section on eBay.

The problem is that I need them to print on the same line. This is what it currently looks like在同一行上打印两个语句。

package main

import (
    "fmt"
    "github.com/gocolly/colly"
)

func main() {
    c := colly.NewCollector(colly.UserAgent("Mozilla/5.0 (X11; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0"))

    c.OnHTML(".s-item__title", func(element *colly.HTMLElement) {
        element.ChildAttr("heading", "role")
        fmt.Println(element.Text)
    })

    c.OnHTML(".s-item__price", func(element *colly.HTMLElement) {
        fmt.Println(element.Text)
    })

    c.Visit("https://www.ebay.com/sch/i.html?_from=R40&_nkw=iPhone&_sacat=0&_pgn=1")
}

It's not even possible to navigate around this information. Can someone show me how I can get the Title along with the price on the same line?

I thought about renaming the element but it didn't work.

I would use printf or println, but then it just prints everything together.

答案1

得分: 1

fmt.Println()在末尾包含了\nln代表换行。如果这是你的问题,你可以使用fmt.Printf()来按照你想要的格式输出,它不会强制换行。

英文:

The fmt.Println() includes '\n' at the end. ln means new line. You can use fmt.PrintF() to format output however you want, it doesn't force a new line, if this is your issue.

答案2

得分: 0

尝试使用fmt.Print而不是fmt.Println

package main

import "fmt"

func main() {
	{
		fmt.Print("Title")
	}
	{
		fmt.Println("| Price")
	}

	{
		fmt.Print("Title")
	}
	{
		fmt.Println("| Price")
	}
}
英文:

Try using fmt.Print instead of fmt.Println

package main

import "fmt"

func main() {
{
	fmt.Print("Title")
}
{
	fmt.Println("| Price")
}

{
	fmt.Print("Title")
}
{
	fmt.Println("| Price")
}
}

huangapple
  • 本文由 发表于 2023年1月19日 18:15:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75170691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定