【学习笔记】Python 3.6模拟输入并爬取百度前10页密切相关链接

【学习笔记】Python 3.6模拟输入并爬取百度前10页密切相关链接

问题描述

通过模拟网页,实现百度搜索关键词,然后获得网页中链接的文本,与准备的文本进行比较,如果有相似之处则代表相关链接。

mechanicalsoup模块

MechanicalSoup无需图形界面环境下的浏览器开源项目,是一个基于极其流行而异常多能的 HTML 解析库 Beautiful Soup 建立的爬虫库。如果你的爬虫需要相当的简单,但是又要求检查一些选择框或者输入一些文字,而你又不想为这个任务单独写一个爬虫,那么这会是一个值得考虑的选择。

安装

pip install MechanicalSoup

需要BeautifulSoup和requests库的依赖。

解析百度网页源码

分析百度网页源代码,找到用来接收搜索关键字的表单和输入框。

 

搜索用的表单

搜索用的表单

 

程序实现

map函数

map函数第一个参数为函数,但不需要'()',第二个参数是迭代器对象,作用是对迭代器对象遍历使用第一个函数。

  1. #!/usr/bin/env python  
  2. #-*- coding:utf-8 -*-  
  3. """  
  4. @author:BanShaohuan 
  5. @file: Python 3.6模拟输入并爬取百度前10页密切相关链接 
  6. @time: 2018/06/09 
  7. @contact: banshaohuan@163.com 
  8. @software: PyCharm  
  9. """  
  10. import mechanicalsoup 
  11.  
  12. # python小屋文章清单 
  13. with open('list.txt', encoding="utf8") as fp: 
  14. articles = fp.readlines() 
  15. #=> 使用map函数,去掉从文本当中读取时的字符,并放入元组中 
  16. articles = tuple(map(str.strip, articles)) 
  17.  
  18. # 模拟打开指定网址,模拟输入并提交输入的关键字 
  19. browser = mechanicalsoup.StatefulBrowser() #=> 新建一个对象 
  20. browser.open(r'http://www.baidu.com')#=> 模拟打开百度 
  21. browser.select_form("#form")#=> 根据class指定一个表单 
  22. browser['wd'] = 'Python小屋'#=> 根据表单的id指定表单中输入的内容 
  23. browser.submit_selected()#=> 提交,模拟搜索 
  24.  
  25. # 获取百度前十页 
  26. top10Urls = [] 
  27. #=> get_current_page得到本页网页,得到a标签对象 
  28. for link in browser.get_current_page().select('a'): 
  29. if link.text in tuple(map(str, range(2, 11))): 
  30. #=> link.attrs['href] a标签中的属性得到值 
  31. top10Urls.append(r'http://www.baidu.com'+ link.attrs['href']) 
  32.  
  33. # 与微信公众号里的文章标题进行比对,如果非常相似就返回True 
  34. def check(text): 
  35. for article in articles: 
  36. # 使用切片,防止网站转发公众号文章时标题不完整 
  37. if article[2:-2].lower() in text.lower(): 
  38. return True 
  39. return False 
  40.  
  41. # 只输出密切相关的链接 
  42. def getLinks(): 
  43. for link in browser.get_current_page().select('a'): 
  44. text = link.text 
  45. if 'Python小屋' in text or '董付国' in text or check(text): 
  46. print(link.text, '-->', link.attrs['href']) 
  47.  
  48. # 输出第一页 
  49. getLinks() 
  50. # 处理后面的9页 
  51. for url in top10Urls: 
  52. browser.open(url) 
  53. getLinks() 

参考内容:Python 3.6模拟输入并爬取百度前10页密切相关链接

原文地址:https://www.cnblogs.com/banshaohuan/p/9160184.html