# 第四章内容--处理不同的网站布局:
# 我们想在功能类似的网站上抓取类似内容时,往往这些网站的内容可能布局不一样(相同内容的标签可能不同),由于通常我们爬取的网站数量有限,
# 我们没有必要去开发比较一套统一的复杂的的算法或机器学习来识别页面上的哪些文字看起来像标题或段落,只需要手动的去检查网页元素,分别对
# 不同的网站采用不同的方式去爬取就好了: # 示例 1:书上的例子,不翻墙没法跑通。
import requests class Content:
def __init__(self, url, title, body):
self.url = url
self.title = title
self.body = body def getPage(url):
req = requests.get(url)
return BeautifulSoup(req.text, 'html.parser') def scrapeNYTimes(url):
bs = getPage(url)
title = bs.find('h1').text
lines = bs.select('div.StoryBodyCompanionColumn div p') # nytime独有的布局
body = '\n'.join([line.text for line in lines])
return Content(url, title, body) def scrapeBrookings(url):
bs = getPage(url)
title = bs.find('h1').text
body = bs.find('div', {'class', 'post-body'}).text # brookings独有的布局
return Content(url, title, body) url = 'https://www.brookings.edu/blog/future-development/2018/01/26/delivering-inclusive-urban-access-3-uncomfortable-truths/'
content = scrapeBrookings(url)
print('Title: {}'.format(content.title))
print('URL: {}\n'.format(content.url))
print(content.body) url = 'https://www.nytimes.com/2018/01/25/opinion/sunday/silicon-valley-immortality.html'
content = scrapeNYTimes(url)
print('Title: {}'.format(content.title))
print('URL: {}\n'.format(content.url))
print(content.body)
# 示例 2: 修改的示例 1
import requests
from bs4 import BeautifulSoup class Content:
def __init__(self, url, title, body):
self.url = url
self.title = title
self.body = body def getPage(url):
html = requests.get(url)
return BeautifulSoup(html.content,'html.parser') # 注,此处使用 html.text时将会导致乱码 def scrapeGushidaquan(url):
bs = getPage(url)
title = bs.find('h2').text
body = bs.find('div', {'class', 'tsrtInfo'}).text # Gushidaquan独有的布局
return Content(url, title, body) def scrapeRensheng5(url):
bs = getPage(url)
title = bs.find('h1').text
body = bs.find_all('p')[0].text # 段落 NavigableString对象.text为 string # Rensheng5独有的布局
return Content(url, title, body) url = 'https://www.gushidaquan.cc/'
content = scrapeGushidaquan(url)
print('Title: {}'.format(content.title))
print('URL: {}\n'.format(content.url))
print(content.body) print("-"*15) url = 'http://www.rensheng5.com/zx/onduzhe/'
content = scrapeRensheng5(url)
print('Title: {}'.format(content.title))
print('URL: {}\n'.format(content.url))
print(content.body)
Title: 故事大全
URL: https://www.gushidaquan.cc/   小三,是通过互联网流行起来的一个词,是对第三者的蔑称。是爱情小说及家庭伦理故事恒久的元素,也是当前不可否认的社会现象。在民间还有狐狸精、邪花等贬称。
今天故事大全小编给您推荐几篇关于小三的精彩故事。有的故事比较长,建议您边看边收藏哦。...
---------------
Title: 读者在线阅读
URL: http://www.rensheng5.com/zx/onduzhe/   《读者》是甘肃人民出版社主办的一份综合类文摘杂志,原名《读者文摘》。  《读者》杂志多年以来始终以弘扬人类优秀文化为己任,坚持“博采中外、荟萃精华、启迪思想、开阔眼界”的办刊宗旨,赢得了各个年龄段和不同阶层读者的喜爱与拥护。  《读者》被誉为“中国人的心灵读本”、“中国期刊第一品牌”。  >>> 读者文摘在线阅读---欢迎您。
# 我们还是有办法来处理针对不同网页布局的爬取的,即把 各网站的不同点:name,url,css选择器等信息作为参数传递给
# bs.find()或 bs.find_all()的 tag/tag_list,attribues_dict参数 ,或传递给 bs.select() 来定义网站的结构及目标数据的位置。 # 总结:
# 3个类:
# content--用来存储所获取的数据的相关信息
# Website--用类来存储目标数据所在网页的 name,url,titleTag,structure等信息
# Crawler--用来爬取数据:获取 bs,解析bs 获取 title,body对象,存储数据信息到 content对象。 # 有一点不明白: url为什么单独给,而不使用 website对象里的 url? class Content:
"""
用来存储所获取的数据的相关信息
"""
def __init__(self, url, title, body):
self.url = url
self.title = title
self.body = body def print(self): # 将 打印或数据持久化的工作封装到函数里。
"""
Flexible printing function controls output
"""
print('URL: {}'.format(self.url))
print('TITLE: {}'.format(self.title))
print('BODY:\n{}'.format(self.body)) class Website:
"""
用类来存储目标数据所在网页的 name,url,titleTag,structure等信息
"""
def __init__(self, name, url, titleTag, bodyTag):
self.name = name
self.url = url
self.titleTag = titleTag
self.bodyTag = bodyTag import requests
from bs4 import BeautifulSoup class Crawler:
# 获取 bs
def getPage(self, url):
try:
html = requests.get(url)
except requests.exceptions.RequestException:
return None
# return BeautifulSoup(html.text, 'html.parser')
return BeautifulSoup(html.content, 'html.parser') # 解析 bs获取 tag对象
def safeGet(self, pageObj, selector):
"""
Utilty function used to get a content string from a Beautiful Soup object and a selector.
Returns an empty string if no objectis found for the given selector
"""
selectedElems = pageObj.select(selector)
if selectedElems is not None and len(selectedElems) > 0:
return '\n'.join([elem.get_text() for elem in selectedElems])
return '' # 调用上面两个方法,并将获得的 tag对象 实例化存储到 Content对象里。
def parse(self, site_obj, url):
"""
调用 getPage()获取包含目标数据的 bs对象,使用 safeGet()解析 bs对象的 title和 body,非空时存储到 content里
"""
bs = self.getPage(url)
if bs is not None:
title = self.safeGet(bs, site_obj.titleTag)
body = self.safeGet(bs, site_obj.bodyTag)
if title != '' and body != '':
content = Content(url, title, body)
content.print() # 调用封装后的 print() if __name__=='__main__':
# # 将要爬取的目标网页的 name,url,tag,cssselector等信息存储在嵌套列表里:
# siteData = [
# ['O\'Reilly Media', 'http://oreilly.com', 'h1', 'section#product-description'],
# ['Reuters', 'http://reuters.com', 'h1', 'div.StandardArticleBody_body_1gnLA'],
# ['Brookings', 'http://www.brookings.edu', 'h1', 'div.post-body'],
# ['New York Times', 'http://nytimes.com', 'h1', 'div.StoryBodyCompanionColumn div p']
# ]
# # 将上述信息实例化成 website对象:
# websites = []
# for site in siteData:
# site_obj=Website(site[0], site[1], site[2], site[3])
# websites.append(site_obj) # crawler = Crawler()
# crawler.parse(websites[0], 'http://shop.oreilly.com/product/0636920028154.do')
# crawler.parse(websites[1], 'http://www.reuters.com/article/us-usa-epa-pruitt-idUSKBN19W2D0')
# crawler.parse(websites[2], 'https://www.brookings.edu/blog/techtank/2016/03/01/idea-to-retire-old-methods-of-policy-education/')
# crawler.parse(websites[3], 'https://www.nytimes.com/2018/01/28/business/energy-environment/oil-boom.html') # 将要爬取的目标网页的 name,url,tag,cssselector等信息存储在嵌套列表里:
siteData = [
['故事大全', 'http://www.brookings.edu', 'h2', 'div.bigtit'],
['人生故事', 'http://nytimes.com', 'p', 'div.zzinfo']
]
# 将上述信息实例化成 website对象:
websites = []
for site in siteData:
site_obj=Website(site[0], site[1], site[2], site[3])
websites.append(site_obj) crawler = Crawler()
crawler.parse(websites[0], 'https://www.gushidaquan.cc/')
crawler.parse(websites[1], 'http://www.rensheng5.com/zx/onduzhe/')
URL: https://www.gushidaquan.cc/
TITLE: 故事大全
每日
故事
爱情故事
鬼故事
故事会
奇谈怪事
民间故事
幽默故事
传奇故事
哲理故事
人生故事
范文
情话大全
健康资讯
BODY: 故事大全
上网看故事,首选故事大全,阅读量排名第一的故事网站! URL: http://www.rensheng5.com/zx/onduzhe/
TITLE:   《读者》是甘肃人民出版社主办的一份综合类文摘杂志,原名《读者文摘》。  《读者》杂志多年以来始终以弘扬人类优秀文化为己任,坚持“博采中外、荟萃精华、启迪思想、开阔眼界”的办刊宗旨,赢得了各个年龄段和不同阶层读者的喜爱与拥护。  《读者》被誉为“中国人的心灵读本”、“中国期刊第一品牌”。  >>> 读者文摘在线阅读---欢迎您。 读者在线阅读_读者文摘在线阅读
Copyright 人生屋 版权所有 BODY: 读者在线阅读
  《读者》是甘肃人民出版社主办的一份综合类文摘杂志,原名《读者文摘》。  《读者》杂志多年以来始终以弘扬人类优秀文化为己任,坚持“博采中外、荟萃精华、启迪思想、开阔眼界”的办刊宗旨,赢得了各个年龄段和不同阶层读者的喜爱与拥护。  《读者》被誉为“中国人的心灵读本”、“中国期刊第一品牌”。  >>> 读者文摘在线阅读---欢迎您。
[人生] 声名20-06-24
有原则的人生最幸福20-06-23
父亲的墨水20-06-22
与母亲相守50天20-06-22
你不是世界的中心20-06-22
海上的父亲20-06-22 [人物] 三老道喜图20-06-22
俯首甘为孺子牛20-06-22
靛蓝商人20-06-22
塬下写作20-06-22
我的小说有辣子和葱20-06-21
见客记20-06-20 [文苑] 海明威的红笔20-06-22
温柔的讲述者20-06-22
我在等你啊20-06-22
春天等不来20-06-21
生有时,寐有时20-06-21
我的目光清澈20-06-20 [社会] 经济学何为20-06-24
给跳蚤穿靴子20-06-24
科技智人20-06-24
常态化偏见20-06-24
相见恨晚20-06-24
帮助别人才是文明的起点20-06-24 [生活] 我的命运是一座花园20-06-24
夜航船20-06-22
当特色菜遇上口味菜20-06-22
为什么看过的电纸书容易忘20-06-22
三泡茶20-06-22
被疫情改变的习惯20-06-22 [文明] 宋画里的医者日常20-06-22
饭不厌诈20-06-22
孤独的52赫兹20-06-20
用人之策20-06-20
“卫生”之起源20-05-22
绘画中的食物20-05-22 [点滴] 蛇与仙鹤20-06-24
真痴20-06-24
山的意义20-06-24
欲望20-06-21
傻气与福气20-06-21
鞋子20-06-21

最新文章

  1. 百度推出新技术 MIP,网页加载更快,广告呢?
  2. 修改Sqlserver实例默认排序规则
  3. logback 配置
  4. 安装protobuf及相关的lua生成器
  5. SpringMVC 简单
  6. poj 2976 Dropping tests
  7. JS于,子类调用父类的函数
  8. 添加zabbix自动发现(监控多tomcat实例)
  9. 【python】函数参数关键字索引、参数指定默认值、搜集参数
  10. 【安卓网络请求开源框架Volley源码解析系列】定制自己的Request请求及Volley框架源码剖析
  11. 【English】20190315
  12. Linux shell 脚本报错:/bin/bash^M: bad interpreter: No such file or directory
  13. 电商项目-商品表(spu)、规格表(sku)设计
  14. mysql练习----Self join
  15. luogu 1640 连续攻击游戏
  16. excel打开csv格式的文件,数字末尾都变成零,解决方式
  17. 【Maven】Select Dependency 无法检索
  18. linux文件查看
  19. TestLink 的使用详解
  20. js 只允许输入数字

热门文章

  1. Python+Appium自动化测试(10)-TouchAction类与MultiAction类(控件元素的滑动、拖动,九宫格解锁,手势操作等)
  2. S3C6410触摸屏驱动分析
  3. 多测师讲解自动化 _rf自动化需要总结的问题(2)_高级讲师肖sir
  4. MeteoInfoLab脚本示例:站点填图
  5. Windows下使用GitStack搭建Git服务器
  6. ps 批量kill进程
  7. C# 获取页面get过来的数据
  8. 彻底理解RSA加密算法
  9. Phoenix的一些问题
  10. Spring Boot 学习摘要--关于配置