分析url的网页源代码,在源代码里有我们想要的评论数据,我们可以用正则(在这里正则还是比较好用的)把我们想要的信息弄下来
开启循环,批量抓取
保存数据至文本和数据库
defparse_one_page(html):
pattern2 = re.compile( '"m_type":"0",(.*?),"username"', re.S)
items=re.findall(pattern2,html)
foritem initems:
item = "{"+ item + "}"
item=json.loads(item)
write_to_file(item)
print(item)
save_to_mongo(item)
#皮皮哥告诉了我他的独家正则匹配方法可以匹配出来,这样的确获得的item没有编码问题
defparse_one_page(html):
pattern = '"content":".*?"'
items=re.findall(pattern,html)
foritem initems:
item =eval(item.split( ':', 1)[ 1])
write_to_file(item)
print(item)
save_to_mongo(item)
#对一般正则写法获得的item进行的方法,这是从皮皮哥那里得知的,亲测有效
defparse_one_page(html):
pattern = re.compile( 'rsion_name".*?"content":(.*?),"username"', re.S)
items=re.findall(pattern,html)
#print(items)
foritem initems:
item = item.encode( 'utf-8').decode( 'unicode_escape')
write_to_file(item)
print(item)
save_to_mongo(item)
三、代码
#config.py
MONGO_URL= 'localhost'
MONGO_DB= 'meituan'
MONGO_TABLE= 'meituan'importrequests
fromrequests.exceptions importRequestException
importjson
importre
fromday31.config import*
importpymongo
client=pymongo.MongoClient(MONGO_URL)
db=client[MONGO_DB]
base_url= 'http://comment.mobilem.360.cn/comment/getComments?callback=jQuery17209056727722758744_1502991196139&baike=%E7%BE%8E%E5%9B%A2%E5%A4%96%E5%8D%96+Android_com.sankuai.meituan.takeoutnew&start='
defthe_url(url):
try:
response = requests.get(url)
ifresponse.status_code== 200:
response.encoding= 'utf-8'
returnresponse.text
returnNone
exceptRequestException:
print( '请求出错')
returnNone
defthe_total():
html=the_url(base_url)
pattern1 = re.compile( '"total":(.*?),"messages"', re.S)
Total = re.findall(pattern1, html)
Total=int( ':'.join(Total))
#print(type(Total))
show= '总计评论%d条'%Total
print(show)
write_to_file(show)
returnTotal
defparse_one_page(html):
pattern2 = re.compile( '"m_type":"0",(.*?),"username"', re.S)
items=re.findall(pattern2,html)
foritem initems:
item = "{"+ item + "}"
item=json.loads(item)
write_to_file(item)
print(item)
save_to_mongo(item)
defsave_to_mongo(result):
try:
ifdb[MONGO_TABLE].insert(result):
print( '储存到MongoDB成功',result)
exceptException:
print( '储存到MongoDB失败',result)
defwrite_to_file(content):
withopen( 'meituan_result.text', 'a',encoding= 'utf-8') asf:
f.write(json.dumps(content,ensure_ascii= False)+ 'n')
f.close()
defmain():
Total=the_total()
Total=int(Total/ 10)+ 2
fori inrange(Total):
url = base_url + str(i* 10)
ifthe_url(url)!= None:
html=the_url(url)
parse_one_page(html)
else:
print( '输完啦')
ps= 'PS:因为有些评论空,所以实际评论比抓取的少'#这是我瞎猜的
write_to_file(ps)
print(ps)
if__name__ == '__main__':
main()
四、最后得到的数据视图和文件
五、总结
1.程序报错很正常,不要一报错就问别人,先自己思考、百度
2.在数据类型处理方面的知识还要加强
3.感谢皮皮哥、感谢姚文峰前辈!
作者:1想得美
链接:http://www.jianshu.com/p/25c8b4cfda1a
作者:1想得美
链接:http://www.jianshu.com/p/25c8b4cfda1a