當我執行用 Go 撰寫的這段代碼時:
package main
import ( "fmt"
"os/exec"
)
func donde(num string) string {
cmd := fmt.Sprintf("wget -qO- \"https://www.pasion.com/contactos-mujeres/%s.htm?edadd=18&edadh=30\"|grep -av \"https:\"|grep -av \"contactos\"|grep -av \"javascript\"|grep -av \"href=\\"/\"", num)
out, err := exec.Command("bash","-c",cmd).Output()
if err != nil {
return fmt.Sprintf("Failed to execute command: %s", cmd)
}
return string(out)
}
func main() {
chicas := map[string][]string{ "Alexia":{"600080000"},
"Paola":{"600070008", "600050007", "600000005", "600000001", "600004", "600000000"}}
for k, v := range chicas {
fmt.Printf("%s\n", k)
for index := range v {
c := donde(v[index])
exec.Command("bash", "-c", c)
fmt.Println(c)}
}
}
我得到:
./favoritas.go:8:189: invalid operation: "wget -qO- \"https://www.pasion.com/contactos-mujeres/%s.htm?edadd=18... / "" (operator / not defined on untyped string)
./favoritas.go:8:190: invalid character U 005C '\'
grep -av \"href=\\"/\"似乎是罪魁禍首。有趣的是,類似的 Python 代碼也可以正常作業:
from subprocess import run
v = "600000005"
dnd = run('wget -qO- \"https://www.pasion.com/contactos-mujeres/' v '.htm?edadd=18&edadh=30\" |grep -av \"https:\"|grep -av \"contactos\"|grep -av \"javascript\" |grep -av \"href=\\"/\"' , capture_output=True, shell=True, text=True, encoding='latin-1').stdout
print(dnd)
并wget -qO- "https://www.pasion.com/contactos-mujeres/600000003.htm?edadd=18&edadh=30" |grep -av "https:"|grep -av "contactos"|grep -av "javascript" |grep -av "href=\"/"從我的 shell 執行(我使用 Bash)也可以正常作業。為什么我不能在我的代碼 Go 中完成相同的操作?我該如何解決這個問題?
PS 這里粘貼的只是更冗長程式的片段。
uj5u.com熱心網友回復:
在一種語言中轉義一種語言中的引號是很困難的。在可用時使用替代語法來減輕這種痛苦。
您的語法很復雜,因為您選擇用雙引號將字串括起來,但字串包含雙引號,因此必須對其進行轉義。此外,字串中的雙引號本身必須被轉義。你已經逃脫了他們,但最后在你的逃脫中做了一個打字:
"wget -qO- \"https://www.pasion.com/contactos-mujeres/%s.htm?edadd=18&edadh=30\"|grep -av \"https:\"|grep -av \"contactos\"|grep -av \"javascript\"|grep -av \"href=\\"/\""
您轉義了反斜杠,但沒有包含額外的反斜杠來轉義引號。所以參考的字串結束了。沒有在/字串中參考,因此作為運算子應用于參考的字串。但是string沒有/運算子,因此錯誤。
`wget -qO- "https://www.pasion.com/contactos-mujeres/%s.htm?edadd=18&edadh=30"|grep -av "https:"|grep -av "contactos"|grep -av "javascript"|grep -av 'href="/'`
關鍵要點:在適當的時候使用反引號來參考包含引號的字串,那么您不需要在字串中轉義引號。
此外,如果您在 bash 中使用單引號,它將禁用所有特殊字符,直到找到另一個單引號。 grep -av 'href="/'更直接,不是嗎?
關鍵要點:在適當的時候在 bash 中使用單引號來描述文字字串
更好的是,除非你真的需要,否則不要掏錢
您在這里的所有痛苦都是因為您采用了在 bash 中有效的代碼,并試圖將其封裝在另一種編程語言中。除非你真的必須這樣做,否則不要這樣做。
在這里考慮一個可能會讓你的生活更輕松的替代方案:
使用 Go 的
net/http庫而不是wget.使用https://pkg.go.dev/golang.org/x/net/html決議回應中的 HTML,這將比
grep. HTML 內容不能很好地 grep。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/432411.html
