1.所需要的库
一般要用到requests库和BeautifulSoup库,这两个库分别用于对网页的获取和分析。但是由于部分网页加载完后会将摘要部分隐藏,需要点击下拉框才可以显示。于是查看了下源代码,定位到“Article preview”后发现有个标志位发生了变化,即aria-expanded="false"变成了aria-expanded="true",查了下该标志位是true表示点击的时候会出现菜单或是浮动元素,false表示没有pop-up效果。再三思索,决定选择selenium+python的方式实现。使用selenium模拟鼠标点击,将所有隐藏摘要显示出,进而获取数据。
另外,数据的整理及保存用到了pandas,openpyxl库;由于文章是英文文章,对于一个考了6次六级的英文小白来说,实现自动化的翻译是最好的!因此还用到了google_trans_new库,这是一个谷歌翻译的API,最初尝试的是googletrans,但是发现运行后会出现trme out,查了下好像是谷歌翻译对该API进行了更新,googletrans不能再使用,最后选择了google_trans_new。
总结下:需要selenium、pandas,openpyxl、google_trans_new四个库。
pip install selenium
pip install pandas
pip install openpyxl
pip intsall google_trans_new
需要注意的是,对于jupyter,只需要在以上命令前加上!即可,速度慢的话,也可以使用国内镜像源:
!pip install selenium -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
from selenium import webdriver
import time
from selenium.webdriver.support.wait import WebDriverWait
import pandas as pd
import datetime
from google_trans_new import google_translator
import openpyxl