今天介绍一下如何使用python来获取Nature官网的文章信息,流程还是和之前的爬虫教程基本一致。
首先我们打开Nature期刊的官网,网址为:https://www.nature.com/
然后我们点击官网右上角的search,输入我们想要文章信息的关键词。
我们以Genetic diversity(遗传多样性)为例做测试。
1.分析目标网址
点击搜索按钮,会出现文章相关信息。
这时我们发现网址为:
https://www.nature.com/search?q=Genetic%20diversity&order=relevance
点击第二页网址为:
https://www.nature.com/search?q=Genetic+diversity&order=relevance&page=2
要获取下一页只需要将数字2改为3,使用其他关键词可以将q后面的内容进行修改。
2. 模拟浏览器发送请求,获取响应内容
这次我们使用python的xpath语法进行网页内容解析.
导入相关包:
import csv
import requests
import time
import random#xpath相关库
from lxml import etree
构造请求头
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',}
使用requests库模拟浏览器发送请求
response = requests.get(url=url,headers=headers).text
3.解析网页内容
使用谷歌浏览器检查发现每个文章信息都放在每个li标签内。
html = etree.HTML(response)
infos = html.xpath('//ul[@class="app-article-list-row"]/li')
通过逐步解析发现各个字段的xpath位置并逐个解析并打印出来:
字段类型有文章题目,文章链接,文章类型,是否开放获取,日期,发表期刊名称
name = info.xpath('./div/article/div[1]/div[2]/h3/a//text() | ./div/article/div[1]/div[1]/h3/a//text()')
#https://www.nature.com/articles/313316a0
articleurl = 'https://www.nature.com' + info.xpath('./div/article/div[1]/div[2]/h3/a/@href | ./div/article/div[1]/div[1]/h3/a/@href')[0]
zongxinxi = info.xpath('./div/article/div[2]//text()')
if len(zongxinxi) == 15:
leixing = zongxinxi[2]
isopen = 'openaccess'
date = zongxinxi[9]
qikanname = zongxinxi[11]
else:
leixing = zongxinxi[2]
isopen = 'closeaccess'
date = zongxinxi[5]
qikanname = zongxinxi[7]print(name,articleurl,leixing,isopen,date,qikanname)
4.将文章信息保存为csv格式
with open('naturearictleinfo.csv', mode='a', newline="") as csvfile:
csv_writer = csv.writer(csvfile, delimiter=',')
csv_writer.writerow([name,articleurl,leixing,isopen,date,qikanname])
打印数据详情
获取多页可使用for循环遍历。
整理数据后:
以上就是全部内容。
十分感谢!