学了一半的python爬虫,今自己摸索着运用先前所学知识写了个项目:
用户输入关键词,便能爬取百度学术上文章标题、作者、摘要、下载链接等(自定义页数),并保存在本地。
最终达到的效果:(以"西方媒体中国偏见”为关键词,爬取两页数据(以减轻服务器压力))
方法一:
需要用到三个模块:
import requests
from bs4 import BeautifulSoup
from urllib.request import quote
将用户输入的信息编码:
#"百度学术是用utf-8编码的,因而这里汉字以这个形式编码
search = input('请输入关键词:')
kwen = search.encode('utf-8') #将汉字,用utf-8格式编码,赋值给gbkkw
新建txt文档,分析百度学术上每页的网址的变化,得出规律:
f = open('百度学术.txt','w',encoding ='utf-8') #创建txt格式文件,方便等会存储
#添加请求头,模拟浏览器正常访问,避免被反爬虫
headers={'user-agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
for x in range(4): #想要爬取多少页数据
url = 'http://xueshu.baidu.com/s?wd='+quote(kwen)+'&pn='+str(x*10)+'&tn=SE_baiduxueshu_c1gjeupa&ie=utf-8&sc_f_para=sc_tasktype%3D%7BfirstSimpleSearch%7D&sc_hit=1'
res = requests.get(url,headers = headers)
print(res.status_code) #查看是否能获取数据
bs1 = BeautifulSoup(res.text, 'html.parser') #解析数据
爬到标题并写入本地:
list_titles = bs1.find_all('div', class_="sc_content")
for i in list_titles:
title = i.find('h3',class_="t c_font").text #爬到标题
print(title)
f.write(title)
因摘要等完整的信息要打开每篇文章链接才能看到,因而在此把每篇文章跳转的链接一并爬出来:
#获取文章跳转链接
half_link = i.find('h3',class_="t c_font").find('a')['href']
wholelink = 'http: