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

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

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

2019-11-14 11:37:47
字體:
來源:轉載
供稿:網友

關于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()


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 高雄县| 五峰| 夏邑县| 平定县| 临沭县| 桑日县| 崇左市| 沙洋县| 景东| 安丘市| 五常市| 三河市| 青田县| 康乐县| 乐至县| 巴青县| 石棉县| 柳州市| 安丘市| 晴隆县| 尼木县| 乌海市| 泸溪县| 漯河市| 聊城市| 奎屯市| 新绛县| 华亭县| 德安县| 大埔区| 萨迦县| 无棣县| 温宿县| 扬州市| 永登县| 平安县| 苍梧县| 崇文区| 彩票| 兰考县| 开封县|