标签(空格分隔): Python 爬虫 2016年暑假html
import urllib.request url = "http://120.27.101.158/" response = urllib.request.urlopen(url) html = response.read() html = html.decode('utf-8'); print (html)
urllib.request.urlopen()
response
对象也相似与文件对象。等价于
```
req = urllib.request.Request("http://placekitten.com/500/600")
response = urllib.request.urlopen(req)python
response.read()
response
对象的读操做,相似的文件对象的读操做.该对象还有如下经常使用方法
```
response.geturl() ##访问的具体地址。
response.info() ##远程的服务器的信息
response.getcode() ##http的状态web
html.decode()
network
中咱们能够看到一些常见的信息url
地址,http
的状态(200)json
格式)json
格式用字典传入一个json
并提交表单,并解析返回来html里的json
,代码以下。正则表达式
import urllib.request '''urllib中的parse用来对url解析''' import urllib.parse import json url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null/' content = input("你想翻译什么呀?") data = {} data['type']='AUTO' data['i'] = content data['doctype'] = 'json' data['xmlVersion'] = '1.8' data['keyfrom'] = 'fanyi.web' data['ue'] = 'UTF-8' data['typoResult'] = 'true' data = urllib.parse.urlencode(data).encode('utf-8') response = urllib.request.urlopen(url, data) html=response.read().decode('utf-8') target =json.loads(html) print ("翻译结果是:%s" %(target['translateResult'][0][0]['tgt']))
> print (target) {'translateResult': [[{'src': '测试程序', 'tgt': 'The test program'}]], 'elapsedTime': 0, 'errorCode': 0, 'smartResult': {'entries': ['', '[计] test program'], 'type': 1}, 'type': 'ZH_CN2EN'}
咱们看到翻译的内容在translateResult[0][0][‘tgt’]中json
data = urllib.parse.urlencode(data).encode('utf-8')
post
,get
进行的字符串,对于中文编码为默认格式的字符串。encode
将该字符串转换为一个字节序列。(从下面程序能够看出其实这个utf-8没什么卵用,换成gbk还会是同样的结果)浏览器
>data >{'type': 'AUTO', 'ue': 'UTF-8', 'typoResult': 'true', 'i': '程序测试', 'xmlVersion': '1.8', 'keyfrom': 'fanyi.web', 'doctype': 'json'} >data = urllib.parse.urlencode(data); #dict转换为str >'type=AUTO&ue=UTF-8&typoResult=true&i=%E7%A8%8B%E5%BA%8F%E6%B5%8B%E8%AF%95&xmlVersion=1.8&keyfrom=fanyi.web&doctype=json' >data = data.encode('utf-8'); #str转换为byte序列 >b'type=AUTO&ue=UTF-8&typoResult=true&i=%E7%A8%8B%E5%BA%8F%E6%B5%8B%E8%AF%95&xmlVersion=1.8&keyfrom=fanyi.web&doctype=json'
response = urllib.request.urlopen(url, data)
data
必须为byte型字符串html=response.read().decode('utf-8')
utf-8
页面解码为unicode
target =json.loads(html)
json
,将其转换为字典import re import urllib.parse import urllib.request #----------模拟浏览器的行为,向谷歌翻译发送数据,而后抓取翻译结果,这就是大概的思路------- def Gtranslate(text): Gtext=text #text 输入要翻译的英文句子 #hl:浏览器、操做系统语言,默认是zh-CN #ie:默认是UTF-8 #text:就是要翻译的字符串 #langpair:语言对,即'en'|'zh-CN'表示从英语到简体中文 values={'hl':'zh-CN','ie':'UTF-8','text':Gtext,'langpair':"auto"} url='http://translate.google.cn/' #URL用来存储谷歌翻译的网址 data = urllib.parse.urlencode(values).encode("utf-8") #将values中的数据经过urllib.urlencode转义为URL专用的格式而后赋给data存储 req = urllib.request.Request(url,data) #而后用URL和data生成一个request browser='Mozilla/4.0 (Windows; U;MSIE 6.0; Windows NT 6.1; SV1; .NET CLR 2.0.50727)' #假装一个IE6.0浏览器访问,若是不假装,谷歌将返回一个403错误 req.add_header('User-Agent',browser) response = urllib.request.urlopen(req) #向谷歌翻译发送请求 html=response.read() #读取返回页面,而后咱们就从这个HTML页面中截取翻译过来的字符串便可 html=html.decode('utf-8') #使用正则表达式匹配<=TRANSLATED_TEXT=)。而翻译后的文本是'TRANSLATED_TEXT='等号后面的内容 p=re.compile(r"(?<=TRANSLATED_TEXT=).*(?=';INPUT_TOOL_PATH='//www.google.com')") m=p.search(html) chineseText=m.group(0).strip(';') return chineseText if __name__ == "__main__": #Gtext为待翻译的字符串 Gtext='我是上帝' print('The input text: %s' % Gtext) chineseText=Gtranslate(Gtext).strip("'") print('Translated End,The output text: %s' % chineseText)
实际的爬虫十分麻烦,要考虑是否被屏蔽,还有登录等等问题。待继续好好学习。服务器
几个资料网络
Python网络爬虫(Get、Post抓取方式)
py爬取英文文档学习单词
python网络爬虫入门(二)——用python简单实现调用谷歌翻译session