<p>Hi,</p>
<p>I'm new to Golang and I'm using <a href="http://go-colly.org/" rel="nofollow">colly</a> to make a simple bot just for testing it.</p>
<p>I have one problem extracting one item from html:</p>
<pre><code>c.OnHTML("div.col.right.more-margin", func(e *colly.HTMLElement) {
name := e.ChildText(".name-icon")
fmt.Printf("name: %s\n", name) // name: chrome
})
</code></pre>
<p>If I want to use variable "name" outside that func, how can I do that?</p>
<p>I need to put that value inside a a struct:</p>
<pre><code>ch <- &Single{ads[value][0].Title, name}
</code></pre>
<p>but var name is always empty.</p>
<p><strong>Thanks</strong></p>
<hr/>**评论:**<br/><br/>justinisrael: <pre><p>You can define your <code>name</code> variable outside that function and then assign the value in the callback.</p>
<pre><code>var name string
c.OnHTML("div.col.right.more-margin", func(e *colly.HTMLElement) {
name = e.ChildText(".name-icon")
fmt.Printf("name: %s\n", name)
})
c.Visit(...)
fmt.Printf("last name seen: %s\n", name)
</code></pre>
<p>This would be a problem if there is more than one match since it would only show the last captured value. So if there are more, you might need a slice. </p></pre>skernel: <pre><p>No, there's only one catch.</p>
<p>Thanks I'll try that code.. </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传