普及一下网页状态码、网页编码的意思:
网页状态码:200(正常访问)301(重定向)403(禁止访问)404(网页不存在)500(服务器忙),我们经常访问外网或者不存在的网站遇到的就是403以及404错误。
网页编码:是指在网页总特定的字符编码格式的库,例如常见的utf-8、GBK、gb 2312等,代码不同的编码格式,utf-8因为其可以在统一显示不同语言,故现如今较为通用。
# -*-coding:utf-8 -*-
#导入库函数并读取URL
import urllib
url = "http://www.baidu.com/"
html = urllib.urlopen(url)
##读取百度网页代码
print html.read()
##读取百度网页状态码
print html.getcode()
html.close()
##保存当前页面至桌面
urllib.urlretrieve(url2,"C:\\USers\\Administrator\\Desktop\\baidu.html")
# -*- coding:utf-8 -*-
import re #正则表达式
import urllib
def get_content(url):
"""doc."""
html = urllib.urlopen(url)
content= html.read()
html.close()
return content
def get_images(info):
"""doc.
j_retract
"""
regex = r'class="BDE_Image" src="(.+?\.jpg)"'
##编译正则表达式
pat = re.compile(regex)
image_code = re.findall(pat,info)
#print image_code
i = 0
for image_url in image_code:
print image_url
urllib.urlretrieve(image_url,'%s.jpg' % i)
i+=1
info = get_content('https://tieba.baidu.com/p/3823765471')
print info
#
#print get_images(info)
# -*- coding:utf-8 -*-
import urllib
from bs4 import BeautifulSoup
def get_content(url):
html = urllib.urlopen(url)
content = html.read()
html.close()
return content
#
def get_images(info):
soup = BeautifulSoup(info)
all_img = soup.find_all('img',class_="BDE_Image")#第二个参数为属性,可得到特定格式
x = 1
##保存图像
for img in all_img:
#print img['src']
image_name = '%s.jpg' % x
urllib.urlretrieve(img['src'],image_name)
x+=1
info = get_content('https://tieba.baidu.com/p/3823765471')
get_images(info
通过这样的方法即可将贴吧中图片保存到本地文件夹