您的位置:首页 > 其它

北京汉传佛寺游人评价数据的抓取与分析(1)

2017-04-05 23:15 351 查看
之前写好的部分明明已经保存了的,为啥就不见了呢mdzz!

要求:

运用Python语言编写网络爬虫获取游客评论数据,借助自然语言处理(NLP)领域中的研究方法挖掘当今人们对寺庙园林的态度和观点,并寻找有趣的可视化方式呈现结果

想法:

抓取寺院粗略信息吗,放入list

经过比较 蚂蜂窝,去哪,携程,大众点评 后发现,蚂蜂窝的数据清洗难度较低

从抓取的寺院中筛选出汉传佛寺放入list

蚂蜂窝好像采取了一定的反爬取措施,遂使用selenium+PhantomJS模拟浏览器的行为

再使用bs4解析上一步抓取到的html文档

此处考虑使用多进程的进行抓取

将bs4解析出来的数据放入MongoDB中

#coding=utf-8
from selenium import webdriver
import time

def get_temple_page_source():

driver = webdriver.PhantomJS()

url = 'http://www.mafengwo.cn/mdd/map/10065.html'

driver.get(url)

time.sleep(1)

driver.find_element_by_css_selector('a[data-channel="search"]').click()
time.sleep(1)

driver.find_element_by_css_selector('div.input_wrapper>input').clear()
driver.find_element_by_css_selector('div.input_wrapper>input').send_keys('寺')
time.sleep(1)

driver.find_element_by_css_selector('div.input_wrapper>span').click()

time.sleep(3)

#reponse_html_page = driver.page_source

#style="overflow: auto; height: 576px;"

#reponse_html_page = driver.find_element_by_css_selector('div.list>ul').text

# print(type(reponse_html_page))
#print(driver.page_source)

pageSource_list = []

pageSource_list.append(driver.page_source)

for i in range(4):
driver.find_element_by_css_selector('div.m-pagination>a.pg-next').click()
time.sleep(3)
#print(driver.page_source)
pageSource_list.append(driver.page_source)

return pageSource_list

if __name__ == "__main__":
get_temple_page_source()


经分析得知,在第五页之前的寺院有一定的评论量,第五页之后的寺院评论量几乎为0,无抓取价值,遂舍弃

尝试抓取的过程中出现的一些状况



本应该是这样的



加上sleep(),让spider睡一会就好了



初步抓取结果



使用bs4处理html文档并放入MongoDB的小测试:





Pycharm的一个快捷键: shift+tab,将所选的代码块整体反向缩进


对搜索结果页面进行抓取的时候发生了字符编码错误:

#coding=utf-8
from bs4 import BeautifulSoup
import pymongo
import requests
from urllib import parse
import pprint
import random

def get_temple_detail_url(search_key_word):

#temple_detail = TempleSpider['temple_detail']

#http://www.mafengwo.cn/search/s.php?q=%E6%BD%AD%E6%9F%98%E5%AF%BA

search_url = 'http://www.mafengwo.cn/search/s.php?q={}'.format(parse.quote(search_key_word, encoding='utf-8'))

search_response = requests.get(search_url)

bsObj = BeautifulSoup(search_response.text, 'lxml')

print(bsObj)

for i in bsObj.select_one('div[data-category="poi"]').find_all("div", class_="clearfix"):
if '景点' in i.find("h3").get_text() and '北京' in i.find_all("li")[0].find("a").get_text():
temple_detail_url = i.find("h3").find("a").get("href")
data = {
'temple_name': search_key_word,
'temple_url': temple_detail_url
}

#print(data)
#temple_detail.insert_one(data)

if __name__ == "__main__":
get_temple_detail_url('潭柘寺')






解决方式如下:



详情参考:requests和BeautifulSoup中文编码转换心得

看样子应该是requests的编码方式出现了问题
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: