python周末吃什么_中午不知道吃什么?用Python爬取美团外卖评论帮你选餐!
分析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
總結
以上是生活随笔為你收集整理的python周末吃什么_中午不知道吃什么?用Python爬取美团外卖评论帮你选餐!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 冲压模板自动标注LISP_自动标注.LS
- 下一篇: idea svn回退版本_mac下使用s