最近搭了个人网站,版面更好看些,地址在 https://mengjiexu.com/

文章目录

  • 获取 Cookies
  • 获取文章列表
    • 网页分析
    • 代码
    • 文章列表
    • 文章年份分布
    • 文章主题分布
  • 爬取文章内容
    • 分析网页
    • 爬取文章代码
    • 爬取文章样例
  • 翻译
    • 翻译文章代码
    • 翻译文章样例
  • 参考文献

从读论文和写论文的体验来看,传闻证据 (anecdotes) 对论文能不能给人可靠的第一印象有决定性作用。传闻证据到位了,就不会有人追着问一些澄清性问题 (clarification questions),后面论证研究题目的重要性时也会顺利很多 (why care)。此外,很多时候传闻证据对作者本人更好地了解研究背景 (institutional background) 并提出合情合理的研究设计也有很大的帮助作用1

据我所知,华尔街日报 (Wall Street Journal) 给很多顶刊论文提供了灵感。比如 Zhu (2019 RFS) 与 用停车场数据预测零售公司业绩的报道非常相关 (2014.11.20 WSJ), 一篇关于对冲基金经理与大数据的报道 (2013.12.18 WSJ) 则提出了 Katona et al. (2018 WP, MS R&R) 和 Mukherjee et al. (2021 JFE) 的主要论点。

所以我最近写论文的时候爬了华尔街日报的所有历史数据,源网址是 WSJ Archives,事实证明这个工作在我最近的论文展示中起到了相当正面的作用2

获取 Cookies

按照惯例,还是先获取 Cookies。首先登陆,登陆后等待大概20秒左右会跳出一个小框,要求接受 cookies,需要点击 YES, I AGREE, 经过这步操作的 Cookies 才能顺利获取文章列表或文章内容,否则会被网站识别为爬虫。

另外, Cookies 有失效时间 (expiry time),最好每次爬之前都更新下 Cookies。

from selenium import webdriver
import time
import jsonoption = webdriver.FirefoxOptions()
option.add_argument('-headless')
driver = webdriver.Firefox(executable_path='/Users/mengjiexu/Dropbox/Pythoncodes/Bleier/geckodriver')# 填入 WSJ 账户信息
email = 'username'
pw = 'password'def login(email, pw):driver.get("https://sso.accounts.dowjones.com/login?")# 为了不透露个人信息,需要读者自己粘贴登陆界面的 urltime.sleep(5)driver.find_element_by_xpath("//div/input[@name = 'username']").send_keys(email)driver.find_element_by_xpath("//div/input[@name = 'password']").send_keys(pw)driver.find_element_by_xpath("//div/button[@type = 'submit']").click()# 登陆
login(email, pw)time.sleep(20)# 切换到跳出的小框
driver.switch_to_frame("sp_message_iframe_490357")
# 点击接受收集 Cookies
driver.find_element_by_xpath("//button[@title='YES, I AGREE']").click()time.sleep(5)# 将 Cookies 写入文件
orcookies = driver.get_cookies()
print(orcookies)
cookies = {}
for item in orcookies:cookies[item['name']] = item['value']
with open("wsjcookies.txt", "w") as f:f.write(json.dumps(cookies))

获取文章列表

网页分析

WSJ 每日文章列表 url 的命名方式十分简单,由以下两部分组成:

  • https://www.wsj.com/news/archive/
  • 年/月/日

所以在指定时间范围内遍历每一天即可得到每一天的文章列表。不过我爬的时候顺手爬了所有的日期列表,所以代码中直接遍历了日期列表。

WSJ Daylist: 链接: https://pan.baidu.com/s/1kPYlot5lmYtQwWlHxA6OpQ 密码: 0b44

以 2021 年 6 月 10 日的文章列表为例 (如下图),对于每一篇文章,主要关注四个变量:

  • 文章所属板块 - 黄色框
  • 文章标题 - 红色框
  • 文章链接 - 绿色框
  • 文章日期 - 前定

很多日期的文章列表都不止一页,所以需要:

  • 判断翻页条件:详见代码中 pagenation(page) 函数
  • 如果满足翻页条件,进行翻页:newdaylink = daylink + "?page=%s"%pagenum

代码
import time
from lxml import etree
import csv
import re
from tqdm import tqdm
import requests
import json
import pandas as pd
import csv
import unicodedata
from string import punctuationf = open('wsjdaylist.txt', 'r')headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0',
"content-type": "application/json; charset=UTF-8",
"Connection": "keep-alive"
}def parsearticle(date, daylink):with open("wsjcookies.txt", "r")as f:cookies = f.read()cookies = json.loads(cookies)session = requests.session()url = "https://www.wsj.com" + daylinkdata = session.get(url, headers=headers, cookies = cookies)time.sleep(1)page = etree.HTML(data.content)href = page.xpath("//h2[@class='WSJTheme--headline--unZqjb45 reset WSJTheme--heading-3--2z_phq5h typography--serif-display--ZXeuhS5E ']/a/@href")sector = page.xpath("//h2[@class='WSJTheme--headline--unZqjb45 reset WSJTheme--heading-3--2z_phq5h typography--serif-display--ZXeuhS5E ']/parent::div[1]/parent::div[1]/preceding-sibling::div[1]//text()[1]")module = [unicodedata.normalize('NFD', i).encode('ascii', 'ignore').decode("utf-8").replace("\n"," ").replace('\t',"") for i in sector if len(i)>1]article = page.xpath("//h2[@class='WSJTheme--headline--unZqjb45 reset WSJTheme--heading-3--2z_phq5h typography--serif-display--ZXeuhS5E ']/a/text()")article = [unicodedata.normalize('NFD', i).encode('ascii', 'ignore').decode("utf-8").replace("\n"," ").replace('\t',"") for i in article]with open("wsjarticlelist_test.csv",'a') as h:k = csv.writer(h)for i in range(len(href)):k.writerow([article[i], module[i], href[i], date])return(page)def pagenation(page):next_page = page.xpath("//span[contains(text(), 'Next Page')]")return(next_page)for line in f:daylink = line.strip()date = daylink.split("/archive/")[-1]page = parsearticle(date, daylink)next_page = pagenation(page)pagenum = 1while next_page:pagenum +=1print(pagenum)newdaylink = daylink + "?page=%s"%pagenumpage = parsearticle(date, newdaylink)next_page = pagenation(page)time.sleep(1)
文章列表

文章年份分布
Year ArticleNum
1997 171
1998 45953
1999 48813
2000 51485
2001 46691
2002 42997
2003 38974
2004 39071
2005 40219
2006 41779
2007 44754
2008 51897
2009 54993
2010 66245
2011 70842
2012 66032
2013 64420
2014 71768
2015 66051
2016 74229
2017 59907
2018 49528
2019 36292
2020 35819
2021 12011
Total 1220941
文章主题分布

排除空白主题,1997-2021年共有 5822 个不同的主题。这里列出使用次数超出 10,000 的主题。

Sector ArticleNum
Business 60119
Markets 34663
U.S. 23402
Heard on the Street 23340
Major Business News 22598
Letters 21531
Politics 20991
Tech Center 18511
Earnings 18178
Technology 17346
U.S. Business News 17109
Europe 15134
Economy 14432
Photos 14290
Review & Outlook 13759
Business and Finance - Europe 13530
Commentary 13428
Health 12979
Business and Finance - Asia 12723
Asia 11163
Bookshelf 11128
World 10833
Media & Marketing 10629
Asian Business News 10428
Commodities 10159
Tech 10153

主题中包含中国的文章有

Sector ArticleNum
China 2008 1
China 2009 1
Snow in China 1
China Stocks 1
China’s Changing Workforce 1
China’s Money Trail 2
China’s Rising Risks 4
China: The People’s Republic at 50 12
My China 12
China Trade Breakthrough 19
China’s World 79
China Circuit 86
Chinas World 127
China News 1101
China 1875
Total 3322

爬取文章内容

分析网页

从网页中获取所有文字信息并不难,但是 WSJ 文章会在文章中插入超链接,如果不做处理的话,爬下来的文字会有很多不符合阅读习惯的换行。我做的处理有:

  • 使用函数 translist(infolist) 筛掉不必要的空格和换行
  • 没有采用直接获取符合条件 html element 下的所有文字的方法,而是对每个 element 进行遍历进行更加精细的筛选。这样做的速度稍微慢一点,但是基本上能呈现比较好的视觉呈现效果
爬取文章代码
import time
from lxml import etree
import csv
import re
from tqdm import tqdm
import requests
import json
import pandas as pd
import csv
import unicodedata
from string import punctuationdf = pd.read_excel("/Users/mengjiexu/Dropbox/wsj0512/wsj0513.xlsx",header=0)headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0',
"content-type": "application/json; charset=UTF-8",
"Connection": "keep-alive"
}def translist(infolist):out = list(filter(lambda s: s and (type(s) != str or len(s.strip()) > 0), [i.strip() for i in infolist]))return(out)def parsearticle(title, date, articlelink):with open("wsjcookies.txt", "r")as f:cookies = f.read()cookies = json.loads(cookies)session = requests.session()data = session.get(articlelink, headers=headers, cookies = cookies)time.sleep(1)page = etree.HTML(data.content)arcontent = title + '\n\n' + date +'\n\n'content = page.xpath("//div[@class='article-content  ']//p")for element in content:subelement = etree.tostring(element).decode()subpage = etree.HTML(subelement)tree = subpage.xpath('//text()')line = ''.join(translist(tree)).replace('\n','').replace('\t','').replace('  ','').strip()+'\n\n'arcontent += linereturn(arcontent)for row in tqdm(df.iterrows()):title = row[1][0].replace('/','-')articlelink = row[1][2]date = row[1][3].replace('/','-')arcontent = parsearticle(title, date, articlelink)with open("/Users/mengjiexu/Dropbox/articles/%s_%s.txt"%(date,title),'w') as g:g.write(''.join(arcontent))
爬取文章样例

翻译

英语阅读速度比较慢的朋友可以调用 百度 API 对文章进行翻译,这样可以一目十行快速提取大量文章信息。为了提高翻译速度,最好整篇文章作为一个文字整体翻译。

翻译文章代码
import os
import requests
import random
import json
from hashlib import md5
from tqdm import tqdmfile_list = os.listdir("/Users/mengjiexu/Dropbox/articles/")# Set your own appid/appkey.
appid = 'xxx'
appkey = 'xxx'# For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
from_lang = 'en'
to_lang =  'zh'endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path# Generate salt and sign
def make_md5(s, encoding='utf-8'):return md5(s.encode(encoding)).hexdigest()salt = random.randint(32768, 65536)
headers = {'Content-Type': 'application/x-www-form-urlencoded'}def trans(query):sign = make_md5(appid + query + str(salt) + appkey)# Build requestpayload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}# Send requestr = requests.post(url, params=payload, headers=headers)result = r.json()# Show responserusult = json.dumps(result, indent=4, ensure_ascii=False)return(result["trans_result"][0]["dst"])for file in tqdm(file_list):content =open("/Users/mengjiexu/Dropbox/articles/%s"%file, 'r').read()print(trans(content.strip()))
翻译文章样例

参考文献

Zhu, Christina. 2019. “Big Data as a Governance Mechanism.” The Review of Financial Studies 32 (5): 2021–61. https://doi.org/10.1093/rfs/hhy081.

Katona, Zsolt, Marcus Painter, Panos N. Patatoukas, and Jean Zeng. 2018. “On the Capital Market Consequences of Alternative Data: Evidence from Outer Space.” SSRN Scholarly Paper ID 3222741. Rochester, NY: Social Science Research Network. https://doi.org/10.2139/ssrn.3222741.

Mukherjee, Abhiroop, George Panayotov, and Janghoon Shon. 2021. “Eye in the Sky: Private Satellites and Government Macro Data.” Journal of Financial Economics, March. https://doi.org/10.1016/j.jfineco.2021.03.002.


  1. 写上对应的英语表达是确保读者理解的意思和我表达的意思不出现偏差而做的一个双重解释。 ↩︎

  2. 获取 WSJ Archive 信息需要购买 WSJ 账号,本文只做交流学习使用,不建议使用本文内容获利。 ↩︎

爬取华尔街日报的历史数据并翻译相关推荐

  1. python 爬取有道词典的翻译 *渔夫版

    前言 在小甲鱼课程里学习到的python爬取有道词典的翻译,发现一些东西不是很适用于现在,网上给出的答案分为两种 一.去掉 "_o" import urllib.request i ...

  2. 使用Python爬取华尔街日报(WALL STREET JOURNAL)全文

    最近由于自己研究需要,写了爬取华尔街日报的爬虫代码.核心是通过selenium并配置缓存文件进行抓取. 为了避免潜在的法律和版权风险,此贴仅供交流学习使用. 导入包 导入的有点多,有一些包是之前的一些 ...

  3. 爬取股票的历史数据(个股)

    股票的历史数据爬取 爬取网易财经的个股历史数据 爬取链接:http://quotes.money.163.com/trade/lsjysj_000001.html? 先爬取股票的对应的代码 爬取股票代 ...

  4. 使用Python爬取简单的有道翻译功能

    python有道翻译功能简单的爬取 首先点开有道翻译官网,审查元素查看Network一栏,输入翻译内容获取translate信息(真正用到翻译功能的就是这个URL) 添加headers信息,代码如下 ...

  5. python 翻译库本地库_利用python爬取并翻译GEO数据库

    原标题:利用python爬取并翻译GEO数据库 GEO数据库是NCBI创建并维护的基因表达数据库,始于2000年,收录了世界各国研究机构提交的高通量基因表达数据,现芯片集数据量高达12万以上.想要从这 ...

  6. Python爬虫实战,简单的爬虫案例,以及爬取百度贴吧网页原码和360翻译

    一.爬取网页上的图片 import requestsresponse = requests.get("http://file.elecfans.com/web1/M00/8B/33/o4YB ...

  7. python爬虫实战之爬取有道翻译

    文章目录 介绍 网页分析 代码实战 当我们学习python爬虫时我们需要做大量的练习,往后我会发布更多的python爬虫练习实战代码,进一步剖析爬虫的每一个细节 介绍 本次爬取的是有道翻译,利用pyt ...

  8. python如何爬取sci论文_利用python爬取并翻译GEO数据库

    GEO数据库是NCBI创建并维护的基因表达数据库,始于2000年,收录了世界各国研究机构提交的高通量基因表达数据,现芯片集数据量高达12万以上.想要从这里面挖掘(bai piao)数据,发个sci提前 ...

  9. Python爬取天气数据,并且进行天气预报(已实现)

    分析任意一个城市的天气状况 先分析网页 爬取数据 获取城市ID 获得城市的昨天与今天的气温 城市多音字问题 爬取城市的历史数据(用到正则匹配)并进行数据清洗 天气数据分析绘图 用机器学习进行气温预测 ...

  10. 【python爬虫】爬取Bing词典的单词存到SQLite数据库

    爬取Bing词典的单词 打算做一个单词相关的app自己用,那词典从何而来呢? 想到了用爬虫.爬哪里的数据呢? 个人比较喜欢微软的东西,所以打算从Bing翻译爬取单词 Bug 由于Bing翻译的html ...

最新文章

  1. nginx resolver 指令的使用
  2. “作为字节跳动面试官,有些话我不得不说!”
  3. pycryptodom的源码安装
  4. mac怎么用python2和3_Mac同时安装python2和python3
  5. 分析redis中大key的几种办法
  6. leetcode 1143. Longest Common Subsequence | 1143. 最长公共子序列(动态规划,暴力递归->傻缓存->dp)
  7. [react] shouldComponentUpdate方法是做什么的
  8. virtualbox版oracle RAC环境搭建
  9. Python 只读属性的实现
  10. 马斯克自曝特斯拉渣产能原因:我错了,过分信任自动化机器人
  11. 修改系统提供视图类的显示字体
  12. Kettle 使用JS加密解密
  13. 制作一个模拟Windows启动界面的文本进度条python
  14. android换肤的实现方案,Android换肤技术总结
  15. 使用WebSocket搭建一个智能聊天系统
  16. [洛谷]P1234 小A的口头禅 (#模拟)
  17. python从入门到弃坑中子弹部分的问题
  18. 计算机定时开机关机设置,电脑定时开关机,小编教你怎么设置电脑定时开关机...
  19. 软件测试之计算机基础
  20. numpy-python的科学计算库

热门文章

  1. Oracle Analyze
  2. 超声波模块的原理介绍之时间函数和digitalRead函数的使用
  3. NoteExpress 文献管理软件及使用相关问题
  4. 国内商务邮箱品牌——TOM企业邮箱
  5. m4125idn如何扫描_京瓷ECOSYS M4125idn驱动
  6. 2012百度移动开发者大会汇报
  7. composer 与php autoload,命名空间
  8. 4-Collection、List、Iterator和泛型
  9. 支付宝小程序对接错误
  10. 【工具推荐】下载github部分文件