python3 一个简单的爬虫-pubmed批量搜索

很久没写了,看看以前的代码颇为不堪回首
anyway,我已非吴下阿蒙!
虽然这个真的很简单就是了

一、 知识点

1、 python 好用小技巧

如何在文本中插入变量?
f'文本内容{插入的变量}'
举例:

print(f'你搜索的{keyword}没有结果')

如何去除前后莫名其妙的空格换行?
string.strip()
举例:

name = 'csapp book \n'
print(name.strip()) #'csapp book'

2、beautifulsoup4 & requests库

谁用谁知道,简单好用,详情网上冲浪plz

3、如何下手

这是爬虫的核心,我的思路一般是:

1、请求部分-得到数据

  • 在f12里找到针对的url和参数
  • 通过请求测试请求和参数
  • 用requests进行请求

2、处理部分-处理数据

  • 用bs4库解析html,这个真的很好用
  • 确定输出的格式,保存到文件,尽量用txt吧,其他格式真是折磨人
    或者有时候不需要解析,用re(即正则表达式)处理一下就行

二、 源码代码

# -*- coding: utf-8 -*
# 请先在命令行运行:pip install requests beautifulsoup4
# 输入文件请在同目录下新建list.txt
# 多个关键词请用+连接(例如 ISG15+mRNA+metabolite)
# 输出文件为同目录下的output.txt
import requests
from bs4 import BeautifulSoup

def get_pubmed(keyword, page, file):
    """
    参数:
        keyword - 搜索的关键词
        page - 搜索的页数
        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):
    """
    参数:
        inp_file - 输入文件
        out_file - 输出文件
        pages - 搜索页数
        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')

你可能感兴趣的:(python3 一个简单的爬虫-pubmed批量搜索)