Beautifulsoup的用法实例

Beautifulsoup主要的功能是从网页抓取数据,相对于正则表达式来说,更简便,具体实例如下:

本文的主要目的是从赛希网下载历年试题,使用Beautifulsoup之前一定要分析网页结构,soup.select和soup.find_all返回的都是列表结构,想要从列表中获取相应的数据,需要遍历列表。此处获取URL仅仅用一句话URL = soup.find_all(href=re.compile("pdf"))就能够实现。非常简便。

再标记一下enumerate()函数,函数传入的是一个序列、迭代器或其他支持迭代对象,返回的是 enumerate(枚举) 对象。

# -*- coding:utf-8 -*-
import re
import sys
import requests
from bs4 import BeautifulSoup

def Download_URL_List():
    url = 'http://www.educity.cn/rk/zhenti/test/'
    user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'
    headers = { 'User-Agent' : user_agent}
    try:
        html = requests.get(url,headers=headers)#连接
    except Exception as e:
        print(e)
    content = html.text#获取内容,自动转码unicode
    soup = BeautifulSoup(content,"lxml")
    URL = soup.find_all(href=re.compile("pdf"))
    return URL

def Download_File(URL):
    pattern = re.compile(r'[a-zA-z]+://[^\s]*.pdf')
    for i,pdf_url in enumerate(URL):
        download_url = ((pattern.search(str(pdf_url))).group(0))
        req = requests.get(download_url)
        string = str(i+1)+'.pdf'
        with open(string,'wb') as pdf:
            pdf.write(req.content)
      
if __name__ == '__main__':
    Download_File(Download_URL_List())
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容