在测试珍爱网用户信息的时候,为什么我这样一直匹配不到?返回空串

来源:15-9 用户信息解析器(下)

脑子笨学不会

2018-10-30

package parser

import (
“regexp”
“strconv”
“ycProject/crawler/engine”
“ycProject/crawler/model”
)
var ageRe = regexp.MustCompile(<td><span class="label">年龄:</span>([\d]+)岁</td>)

var marriageRe = regexp.MustCompile(<td><span class="label">婚况:</span>([^<]+)</td>)

var IncomeRe = regexp.MustCompile(<td><span class="label">月收入:</span>([^<]+)元</td>)
var weightRe = regexp.MustCompile(<td><span class="label">体重:</span><span field="">(\d+)KG</span></td>)
var heightRe = regexp.MustCompile(<td><span class="label">身高:</span>([\d]+)CM</td>)
var genderRe = regexp.MustCompile(<td><span class="label">性别:</span><span field="">([^<]+)</span></td>)
var xingzuoRe = regexp.MustCompile( 星座:([^<]+)`)

var educationRe = regexp.MustCompile(<td><span class="label">学历:</span>([^<]+)</td>)
var occupationRe = regexp.MustCompile(<td><span class="label">职业:</span><span field="">([^<]+)</span></td>)
var hukouRe = regexp.MustCompile(<td><span class="label">籍贯:</span>([^<]+)</td>)
var houseRe = regexp.MustCompile(<td><span class="label">住房条件:</span><span field="">([^<]+)</span></td>)
var carRe = regexp.MustCompile(<td><span class="label">是否购车:</span><span field="">([^<]+)</span></td>)

func ParseProfile(contents []byte) engine.ParseResult {
profile := model.Profile{}
age, err := strconv.Atoi(
extractString(contents, ageRe))
if err == nil {
profile.Age = age
}
height, err := strconv.Atoi(extractString(contents, heightRe))
if err == nil {
profile.Height = height
}
weight, err := strconv.Atoi(extractString(contents, weightRe))
if err == nil {
profile.Weight = weight
}

profile.Income = extractString(
	contents, IncomeRe)
profile.Gender = extractString(
	contents, genderRe)
profile.Car = extractString(
	contents, carRe)
profile.Education = extractString(
	contents, educationRe)
profile.Hukou = extractString(
	contents, hukouRe)
profile.House = extractString(
	contents, houseRe)
profile.Marriage = extractString(
	contents, marriageRe)
profile.Occupation = extractString(
	contents, occupationRe)
profile.Xingzuo = extractString(
	contents, xingzuoRe)                           
result := engine.ParseResult{
	Items: []interface{} {profile},
}
return result

}

func extractString(contents []byte, re *regexp.Regexp) string {
match := re.FindSubmatch(contents)
if len(match) >= 2 {
return string(match[1])
} else {
return “”
}
}
这个是做测试结果
图片描述

写回答

2回答

ccmouse

2018-11-03

这样的问题使用调试器很容易发现。我还没有看代码,不过最容易出错的是正则表达式匹配出来的结果。这个如果不对的话,只能通过一步一步去掉正则表达式里的东西,直到匹配到一些内容,然后再一步一步加回去,看看哪里错了

0
1
脑子笨学不会
非常感谢!谢谢老师
2018-11-05
共1条回复

脑子笨学不会

提问者

2018-11-10

自己已经解决了,不是代码的问题,是测试用的文件html的问题,在网上复制源代码的时候,一定要用没有被浏览器排版好的代码,如果复制了被浏览器排版好的代码,就会匹配不出来

0
0

Google资深工程师深度讲解Go语言 由浅入深掌握Go语言

语法+分布式爬虫实战 为转型工程师量身打造

5995 学习 · 1908 问题

查看课程