因为任务的要求,需要爬取百度知道的一些问答信息。仅仅使用urllib或者其他获取页面信息的手段是不行的。
因为百度知道的页面是通过ajax异步加载的,所以我们需用使用到selenium 和 PhantomJS,其中PhantomJS是headless 的 webkit服务器端,能够模拟JS环境。
这样我们就能获取完整的页面信息,并且可以进行模拟点击等操作
1 百度知道列表页面分析
https://zhidao.baidu.com/list?cid=101
包含了一系列的问题列表
查看代码
模拟实现的代码
if driver.page_source.find('pTag next disabled') != -1:
break
# 模拟点击下一页
time.sleep(1)
elem = driver.find_element_by_class_name('next')
elem.click()
soup = BeautifulSoup(driver.page_source, 'html.parser')
self.handle_page_info(soup)
使用 time.sleep(1),等待1S,避免页面未能及时更新
2 百度知道问题页面分析
查看代码(部分)
使用BeautifulSoup提取里面的内容信息
try:
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
question = soup.find_all('title')[0].get_text()
Keywords = soup.find_all('meta', {'name': 'keywords'})[0].get('content')
Description = soup.find_all('meta', {'name': 'description'})[0].get('content')
except:
print "链接失效"
3 多进程设计
# 获取url参数列表
url_list = Question.mul_get_url()
#print url_list
while len(url_list) > 0:
# 创建线程池
#pool = threadpool.ThreadPool(10)
pool = threadpool.ThreadPool(5)
requests = threadpool.makeRequests(create_job, url_list)
[pool.putRequest(req) for req in requests]
pool.wait()
url_list = Question.mul_get_url()
4 源码(使用了redis保存URL和已经爬取的URL信息)
地址:
https://github.com/xuwenkang/laboratory.git