python爬虫爬取Bloomberg新闻

2023-10-08 19:30

本文主要是介绍python爬虫爬取Bloomberg新闻,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近在爬取bloomberg上的新闻,所以在这里记录一下过程。

思路

通过网站的sitemap获取链接,解析链接通过scrapy框架爬取。


网站链接的获取:

https://www.bloomberg.com/robots.txt 这是网站的robots.txt,如下:
# Bot rules:
# 1. A bot may not injure a human being or, through inaction, allow a human being to come to harm.
# 2. A bot must obey orders given it by human beings except where such orders would conflict with the First Law.
# 3. A bot must protect its own existence as long as such protection does not conflict with the First or Second Law.
# If you can read this then you should apply here https://www.bloomberg.com/careers/
User-agent: *
Disallow: /news/live-blog/2016-03-11/bank-of-japan-monetary-policy-decision-and-kuroda-s-briefing
Disallow: /polska
User-agent: Mediapartners-Google*
Disallow: /about/careers
Disallow: /about/careers/
Disallow: /offlinemessage/
Disallow: /apps/fbk
Disallow: /bb/newsarchive/
Disallow: /apps/news
Sitemap: https://www.bloomberg.com/feeds/bbiz/sitemap_index.xml
Sitemap: https://www.bloomberg.com/feeds/bpol/sitemap_index.xml
Sitemap: https://www.bloomberg.com/feeds/bview/sitemap_index.xml
Sitemap: https://www.bloomberg.com/feeds/gadfly/sitemap_index.xml
Sitemap: https://www.bloomberg.com/feeds/quicktake/sitemap_index.xml
Sitemap: https://www.bloomberg.com/bcom/sitemaps/people-index.xml
Sitemap: https://www.bloomberg.com/bcom/sitemaps/private-companies-index.xml
Sitemap: https://www.bloomberg.com/feeds/bbiz/sitemap_securities_index.xml
User-agent: Spinn3r
Disallow: /podcasts/
Disallow: /feed/podcast/
Disallow: /bb/avfile/
User-agent: Googlebot-News
Disallow: /sponsor/
Disallow: /news/sponsors/*

其中红色部分是我们要爬取的sitemap,打开其中一个,会有如下的xml文件:
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>
https://www.bloomberg.com/feeds/gadfly/sitemap_recent.xml
</loc>
<lastmod>2017-02-17T07:46:07-05:00</lastmod>
</sitemap>
<sitemap>
<loc>
https://www.bloomberg.com/feeds/gadfly/sitemap_news.xml
</loc>
<lastmod>2017-02-17T07:46:07-05:00</lastmod>
</sitemap>
<sitemap>
<loc>
https://www.bloomberg.com/feeds/gadfly/sitemap_2017_2.xml
</loc>
<lastmod>2017-02-17T07:46:07-05:00</lastmod>
</sitemap>



我们需要提取其中的<loc>*</loc>中的内容,这仍然是sitemap,打开后如下:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
<loc>
https://www.bloomberg.com/gadfly/articles/2017-02-17/luxury-tax
</loc>
<news:news>
<news:publication>
<news:name>Bloomberg</news:name>
<news:language>en</news:language>
</news:publication>
<news:title>Giving U.S. Border Tax a European Luxury Snub</news:title>
<news:publication_date>2017-02-17T10:43:15.284Z</news:publication_date>
<news:keywords>
Sales Tax, Jobs, China, Europe, Ralph Lauren, Michael David Kors, Bernard Arnault, Donald John Trump, Miuccia Prada Bianchi
</news:keywords>
<news:stock_tickers>LON:BRBY, EPA:MC, LON:BARC, EPA:KER</news:stock_tickers>
</news:news>
<image:image>
<image:loc>
https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iurmUVIRXTqY/v0/1200x-1.jpg
</image:loc>
<image:license>https://www.bloomberg.com/tos</image:license>
</image:image>
</url>


<loc>标签中的内容就是我们需要爬取的新闻地址。

第一步,要获得所有的新闻地址,代码如下:

# -*- coding: utf-8 -*-
#可以下载网站的sitemap
import re
from downloader import Downloader #downloader的作用是下载网页内容
D = Downloader()file1 = open('sitemaps.txt','a')
file2 = open('htmls.txt','a')
def crawl_sitemap(url):#download sitemap filesitemap = D(url)#extract the sitemap linkslinks = re.findall('<loc>(.*?)</loc>',sitemap)#download each linkfor link in links:file1.write(link)file1.write('\n')html = D(link)file2.write(html)file2.write('\n')
crawl_sitemap('https://www.bloomberg.com/feeds/gadfly/sitemap_index.xml')#上面四个红色的sitemap,这里就放了一个,没有写到一起。file1.close()
file2.close()

downloader文件:
import urlparse
import urllib2
import random
import time
from datetime import datetime, timedelta
import socketDEFAULT_AGENT = 'wswp'
DEFAULT_DELAY = 5
DEFAULT_RETRIES = 1
DEFAULT_TIMEOUT = 60class Downloader:def __init__(self, delay=DEFAULT_DELAY, user_agent=DEFAULT_AGENT, proxies=None, num_retries=DEFAULT_RETRIES,timeout=DEFAULT_TIMEOUT, opener=None, cache=None):socket.setdefaulttimeout(timeout)self.throttle = Throttle(delay)self.user_agent = user_agentself.proxies = proxiesself.num_retries = num_retriesself.opener = openerself.cache = cachedef __call__(self, url):result = Noneif self.cache:try:result = self.cache[url]except KeyError:# url is not available in cachepasselse:if self.num_retries > 0 and 500 <= result['code'] < 600:# server error so ignore result from cache and re-downloadresult = Noneif result is None:# result was not loaded from cache so still need to downloadself.throttle.wait(url)proxy = random.choice(self.proxies) if self.proxies else Noneheaders = {'User-agent': self.user_agent}result = self.download(url, headers, proxy=proxy, num_retries=self.num_retries)if self.cache:# save result to cacheself.cache[url] = resultreturn result['html']def download(self, url, headers, proxy, num_retries, data=None):print 'Downloading:', urlrequest = urllib2.Request(url, data, headers or {})opener = self.opener or urllib2.build_opener()if proxy:proxy_params = {urlparse.urlparse(url).scheme: proxy}opener.add_handler(urllib2.ProxyHandler(proxy_params))try:response = opener.open(request)html = response.read()code = response.codeexcept Exception as e:print 'Download error:', str(e)html = ''if hasattr(e, 'code'):code = e.codeif num_retries > 0 and 500 <= code < 600:# retry 5XX HTTP errorsreturn self._get(url, headers, proxy, num_retries - 1, data)else:code = Nonereturn {'html': html, 'code': code}def _get(self, url, headers, proxy, param, data):passclass Throttle:"""Throttle downloading by sleeping between requests to same domain"""def __init__(self, delay):# amount of delay between downloads for each domainself.delay = delay# timestamp of when a domain was last accessedself.domains = {}def wait(self, url):"""Delay if have accessed this domain recently"""domain = urlparse.urlsplit(url).netloclast_accessed = self.domains.get(domain)if self.delay > 0 and last_accessed is not None:sleep_secs = self.delay - (datetime.now() - last_accessed).secondsif sleep_secs > 0:time.sleep(sleep_secs)self.domains[domain] = datetime.now()
通过以上的代码,我们得到了对应sitemap下的xml文件


然后提取其中的<loc> </loc>标签的内容:
import re
file = open('./sitemap_and_html_waiting_to_be_crawled/htmls_gadfly.txt')
file2 = open('htmls.txt','a')for temp in file.readlines():if re.match('<loc>',temp.strip()) is None:passelse:print temp#file2.write(temp)#file2.write('\n')
file.close()
file2.close()

得到的文件中还会有<loc>标签,直接用文本编辑去掉就行,最后的文件形式是这样的:


另外的几个sitemap改一下上面第一段代码中的地址就行了。这样就获取了全部的新闻地址,接下来开始爬取新闻内容。

——————————————割——————————————————————————————————————————————————————————————

scrapy爬虫

爬虫教程:https://doc.scrapy.org/en/1.3/intro/tutorial.html
这里需要一些安装,都很容易,打开cmd在一个目录下输入:
scrapy startproject linkcrawler
这样就创建了一个scrapy爬虫,在spiders目录下,创建爬虫文件,写入代码:
import scrapy
file = open('G:\onedrive\workspace\crawler\htmls\htmls_gadfly.txt')#这里是之前html文件的地址
data = file.readlines()def list_to_string(list):string = ""for i in list:string += i.strip()return stringclass LinkCrawler(scrapy.Spider):name = "link"def start_requests(self):"""urls = ['https://www.bloomberg.com/gadfly/articles/2017-02-16/baidu-failing-fast-is-a-smart-move-to-build-a-future','https://www.bloomberg.com/gadfly/articles/2017-02-13/gaslog-partners-poised-for-lng-market-recovery','https://www.bloomberg.com/gadfly/articles/2017-02-07/bp-earnings-today-doesn-t-match-tomorrow']:return:"""for url in data:yield scrapy.Request(url=url, callback=self.parse)def parse(self, response): #这里是比较关键的部分,主要用了css选择器,选择需要的部分,下面会详细讲yield{'title': response.css('h1.headline_4rK3h>a::text').extract_first(),'time_1': response.css("time::text").extract_first().strip(),'time_2': response.css('time').re(r'datetime="\s*(.*)">')[0],'content': list_to_string(response.css('div.container_1KxJx>p::text').extract())}file.close()

这就是全部代码了,很easy啊。
还是刚才的cmd窗口,输入
scrapy crawl link -o news.json
 经过一段时间的运行,就把所有的新闻保存在一个news.json文件中了。


css选择器:

我们得到网页链接之后最重要的就是分析网页内容,选择我们想要的内容,这部分其实很多方法,包括正则表达式,beautifulsoup,lxml,我们直接用scrapy自带的css选择器进行选择。
随意打开一个网页,首先是标题:如下所示


我们关注的部分是:

在命令行中打开scrapy shell:、

后面是网址。
在scrapy shell中输入
response.css('h1.headline_4rK3h>a::text').extract_first()
可以看到标题就提取出来了。
还有一点就是爬取bloomberg的时候一定要能上Google,最好是全局代理,不然是连不上的。

总结

原理很简单就是通过网站的sitemap进行爬取,代码写的有点罗嗦,不过功能是实现了,可以比较稳定快速的爬取bloomberg的新闻,第一次发博客,希望如果有大神看到能指点一二。

这篇关于python爬虫爬取Bloomberg新闻的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/167530

相关文章

Python远程控制MySQL的完整指南

《Python远程控制MySQL的完整指南》MySQL是最流行的关系型数据库之一,Python通过多种方式可以与MySQL进行交互,下面小编就为大家详细介绍一下Python操作MySQL的常用方法和最... 目录1. 准备工作2. 连接mysql数据库使用mysql-connector使用PyMySQL3.

使用Python实现base64字符串与图片互转的详细步骤

《使用Python实现base64字符串与图片互转的详细步骤》要将一个Base64编码的字符串转换为图片文件并保存下来,可以使用Python的base64模块来实现,这一过程包括解码Base64字符串... 目录1. 图片编码为 Base64 字符串2. Base64 字符串解码为图片文件3. 示例使用注意

使用Python实现获取屏幕像素颜色值

《使用Python实现获取屏幕像素颜色值》这篇文章主要为大家详细介绍了如何使用Python实现获取屏幕像素颜色值,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 一、一个小工具,按住F10键,颜色值会跟着显示。完整代码import tkinter as tkimport pyau

python编写朋克风格的天气查询程序

《python编写朋克风格的天气查询程序》这篇文章主要为大家详细介绍了一个基于Python的桌面应用程序,使用了tkinter库来创建图形用户界面并通过requests库调用Open-MeteoAPI... 目录工具介绍工具使用说明python脚本内容如何运行脚本工具介绍这个天气查询工具是一个基于 Pyt

Python FastMCP构建MCP服务端与客户端的详细步骤

《PythonFastMCP构建MCP服务端与客户端的详细步骤》MCP(Multi-ClientProtocol)是一种用于构建可扩展服务的通信协议框架,本文将使用FastMCP搭建一个支持St... 目录简介环境准备服务端实现(server.py)客户端实现(client.py)运行效果扩展方向常见问题结

详解如何使用Python构建从数据到文档的自动化工作流

《详解如何使用Python构建从数据到文档的自动化工作流》这篇文章将通过真实工作场景拆解,为大家展示如何用Python构建自动化工作流,让工具代替人力完成这些数字苦力活,感兴趣的小伙伴可以跟随小编一起... 目录一、Excel处理:从数据搬运工到智能分析师二、PDF处理:文档工厂的智能生产线三、邮件自动化:

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061

Python中文件读取操作漏洞深度解析与防护指南

《Python中文件读取操作漏洞深度解析与防护指南》在Web应用开发中,文件操作是最基础也最危险的功能之一,这篇文章将全面剖析Python环境中常见的文件读取漏洞类型,成因及防护方案,感兴趣的小伙伴可... 目录引言一、静态资源处理中的路径穿越漏洞1.1 典型漏洞场景1.2 os.path.join()的陷

Python数据分析与可视化的全面指南(从数据清洗到图表呈现)

《Python数据分析与可视化的全面指南(从数据清洗到图表呈现)》Python是数据分析与可视化领域中最受欢迎的编程语言之一,凭借其丰富的库和工具,Python能够帮助我们快速处理、分析数据并生成高质... 目录一、数据采集与初步探索二、数据清洗的七种武器1. 缺失值处理策略2. 异常值检测与修正3. 数据