国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

使用BeautifulSoup提取網頁信息并自動存儲

2019-11-14 12:06:09
字體:
來源:轉載
供稿:網友

關于BeautifulSoup類的實例方法和屬性的說明,不再贅述,還是拿示例分析,看一看使用BeautifulSoup是如何提取網站信息并自動存儲的。

下面的例子是用提供的網站域名作為文件夾名稱,把提取到的圖像文件存儲到文件夾中。

from bs4 import BeautifulSoupimport requestsimport osfrom urllib.request import urlopenfrom urllib.parse import urlparse'''if len(sys.argv) < 2:    PRint("用法:python bs4FileTest.py 網址")    exit(1)'''url = 'http://www.abvedu.com/appcpzs'domain = "{}://{}".format(urlparse(url).scheme, urlparse(url).hostname)#http://www.abvedu.comsrc = requests.get(url)print(type(src))src.encoding = 'bgk'#獲得以標記為元素的文本列表html  = src.text#對超文本標記語言進行解析,生成一個BeautifulSoup實例bsbs = BeautifulSoup(html,'html.parser')#搜索的目標是<img>標簽,把搜索到的符合條件的標簽存放到列表all_imgs中all_imgs = bs.find_all(['a','img'])#all_imgs = bs.find_all(['img'])#迭代列表for link in all_imgs:    #提取屬性值,即從<img..../>標簽中提取屬性    src = link.get('src')    print("-----",src,"------------")    href = link.get('href')    print("**********",href,"**********")    #創建一個列表    targets = [src, href]    for t in targets:        if t != None and ('.jpg' in t or '.png' in t or 'gif' in t):            if t.startswith('http'): full_path = t            else:                     full_path = domain+t            print(full_path)            image_dir = url.split('/')[-1]            #檢查要存取的文件夾是否存在,如果不存在就創建一個新的            if not os.path.exists(image_dir): os.mkdir(image_dir)            filename = full_path.split('/')[-1]            ext = filename.split('.')[-1]            filename = filename.split('.')[-2]            if  'jpg' in ext: filename = filename + '.jpg'            else:              filename = filename + '.png'            image = urlopen(full_path)            fp = open(os.path.join(image_dir,filename),'wb')            fp.write(image.read())            fp.close()


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 特克斯县| 靖远县| 元朗区| 墨江| 自治县| 南城县| 杨浦区| 郧西县| 新田县| 望都县| 宁乡县| 香河县| 安新县| 措美县| 凤庆县| 桑日县| 海盐县| 南投县| 高阳县| 安康市| 原阳县| 新乡市| 晋江市| 乌恰县| 祁门县| 榆社县| 天长市| 泽州县| 镶黄旗| 岐山县| 砚山县| 肇东市| 行唐县| 柳州市| 龙门县| 仙桃市| 永康市| 兴城市| 工布江达县| 林周县| 喜德县|