很久沒寫了,看看以前的代碼頗為不堪回首
anyway,我已非吳下阿蒙钉迷!
雖然這個(gè)真的很簡(jiǎn)單就是了
一、 知識(shí)點(diǎn)
1钠署、 python 好用小技巧
如何在文本中插入變量糠聪?
f'文本內(nèi)容{插入的變量}'
舉例:
print(f'你搜索的{keyword}沒有結(jié)果')
如何去除前后莫名其妙的空格換行?
string.strip()
舉例:
name = 'csapp book \n'
print(name.strip()) #'csapp book'
2谐鼎、beautifulsoup4 & requests庫(kù)
誰(shuí)用誰(shuí)知道舰蟆,簡(jiǎn)單好用,詳情網(wǎng)上沖浪plz
3狸棍、如何下手
這是爬蟲的核心身害,我的思路一般是:
1、請(qǐng)求部分-得到數(shù)據(jù)
- 在f12里找到針對(duì)的url和參數(shù)
- 通過請(qǐng)求測(cè)試請(qǐng)求和參數(shù)
- 用requests進(jìn)行請(qǐng)求
2草戈、處理部分-處理數(shù)據(jù)
- 用bs4庫(kù)解析html塌鸯,這個(gè)真的很好用
- 確定輸出的格式,保存到文件唐片,盡量用txt吧丙猬,其他格式真是折磨人
或者有時(shí)候不需要解析涨颜,用re(即正則表達(dá)式)處理一下就行
二、 源碼代碼
# -*- coding: utf-8 -*
# 請(qǐng)先在命令行運(yùn)行:pip install requests beautifulsoup4
# 輸入文件請(qǐng)?jiān)谕夸浵滦陆╨ist.txt
# 多個(gè)關(guān)鍵詞請(qǐng)用+連接(例如 ISG15+mRNA+metabolite)
# 輸出文件為同目錄下的output.txt
import requests
from bs4 import BeautifulSoup
def get_pubmed(keyword, page, file):
"""
參數(shù):
keyword - 搜索的關(guān)鍵詞
page - 搜索的頁(yè)數(shù)
file - 輸出文件
"""
url = 'https://pubmed.ncbi.nlm.nih.gov'
rep = requests.get(f'{url}/?term={keyword}&page={page}')
html = BeautifulSoup(rep.text, features='html.parser')
li = html.find_all(class_='docsum-title')
if len(li):
for index, item in enumerate(li):
file.write(f"{index+1+(page-1)*10}\t{url}{item['href']}\t{item.text.strip()}\n")
print(f'get {keyword} page {page} success')
return True
return False
def main(inp_file, out_file, pages, mode):
"""
參數(shù):
inp_file - 輸入文件
out_file - 輸出文件
pages - 搜索頁(yè)數(shù)
mode - 輸出模式 a/w 追加/覆寫
"""
print(f'read file {inp_file}, save result in {out_file}')
outfile = open(out_file, mode)
with open(inp_file, 'r') as file:
keyword= file.readline().strip()
while keyword:
outfile.write(f'search word: {keyword}\n')
for page in range(pages):
if not get_pubmed(keyword, page+1, outfile):
if page==0:
outfile.write(f'\t{keyword} has no result find')
print(f'\t{keyword} has no result find')
break
keyword = file.readline().strip()
outfile.close()
print('done')
main('list.txt', 'output.txt', 5, 'w')