2015-06-02 09:32
采纳率: 100%
浏览 150


Hello again everybody,

I apologize for asking another question so soon, but it just seems to be one thing after another with Go lately.

I have a working web page scraper (thanks to everybody's help) that grabs all the info I want from this wiki page:

It then displays everything I want, no hiccups. However, when I go to write to a .txt file I get an error stating: "0 write mh4u.txt: The handle is invalid"

Here is my current code for reference:

package main

import (


func main() {

    filename := "mh4u.txt"
    file, err := os.Create(filename)

    if err!= nil {
    doc, err := goquery.NewDocument("")
    if err != nil {

    doc.Find("tbody").Each(func(i int, s *goquery.Selection) {

        s.Find("td").Each(func(j int, s2 *goquery.Selection) {

            if s3 := s2.Find("img"); s3 != nil && s3.Length() > 0 {

            n, err := io.WriteString(file, s2.Text())

            if err != nil {
                fmt.Println(n, err) 


Testing this code with other web sites leads me to believe that there is maybe some hidden characters that is giving the writer some issues, but that's the only thing I can guess.

Thanks so much for any suggestions/tips/solutions you can offer!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dongsuichi6529 2015-06-02 09:39

    You're calling file.Close() inside a closure. If doc.Find("tbody").Each is called more than one time, you'll end up trying to write to a closed file. You should defer the file closing right after you've created it:

    file, err := os.Create(filename)
    if err != nil {
    defer file.Close()
    解决 无用
    打赏 举报

相关推荐 更多相似问题