1. 用python抓取编码为gb2312的网页,结果抓取的都是乱码 怎样才能将它弄成正常的HTML格式
你试试下面的代码
#!/usr/bin/envpython
#-*-coding:utf8-*-
importurllib2
req=urllib2.Request("http://www..com/")
res=urllib2.urlopen(req)
html=res.read()
res.close()
html=unicode(html,"gb2312").encode("utf8")
printhtml
2. python抓取网页print字符编码问题
string.decode('gbk').encode('utf8')
3. python用requests获取网页源代码为什么中文显示错误
你用的啥?Python2?urllib?Python3只需要html
=
urllib.
request.
urlope('http://
music.
.
com').
read()即可,不难啊。也不会有乱码这东西(不排除本身网站土)。
4. python爬虫怎么获取动态的网页源码
一个月前实习导师布置任务说通过网络爬虫获取深圳市气象局发布的降雨数据,网页如下:
心想,爬虫不太难的,当年跟zjb爬煎蛋网无(mei)聊(zi)图的时候,多么清高。由于接受任务后的一个月考试加作业一大堆,导师也不催,自己也不急。
但是,导师等我一个月都得让我来写意味着这东西得有多难吧。。。今天打开一看的确是这样。网站是基于Ajax写的,数据动态获取,所以无法通过下载源代码然后解析获得。
从某不良少年写的抓取淘宝mm的例子中收到启发,对于这样的情况,一般可以同构自己搭建浏览器实现。phantomJs,CasperJS都是不错的选择。
导师的要求是获取过去一年内深圳每个区每个站点每小时的降雨量,执行该操作需要通过如上图中的历史查询实现,即通过一个时间来查询,而这个时间存放在一个hidden类型的input标签里,当然可以通过js语句将其改为text类型,然后执行send_keys之类的操作。然而,我失败了。时间可以修改设置,可是结果如下图。
为此,仅抓取实时数据。选取python的selenium,模拟搭建浏览器,模拟人为的点击等操作实现数据生成和获取。selenium的一大优点就是能获取网页渲染后的源代码,即执行操作后的源代码。普通的通过 url解析网页的方式只能获取给定的数据,不能实现与用户之间的交互。selenium通过获取渲染后的网页源码,并通过丰富的查找工具,个人认为最好用的就是find_element_by_xpath("xxx"),通过该方式查找到元素后可执行点击、输入等事件,进而向服务器发出请求,获取所需的数据。
[python]view plain
#coding=utf-8
fromtestStringimport*
fromseleniumimportwebdriver
importstring
importos
fromselenium.webdriver.common.keysimportKeys
importtime
importsys
default_encoding='utf-8'
ifsys.getdefaultencoding()!=default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
district_navs=['nav2','nav1','nav3','nav4','nav5','nav6','nav7','nav8','nav9','nav10']
district_names=['福田区','罗湖区','南山区','盐田区','宝安区','龙岗区','光明新区','坪山新区','龙华新区','大鹏新区']
flag=1
while(flag>0):
driver=webdriver.Chrome()
driver.get("hianCe/")
#选择降雨量
driver.find_element_by_xpath("//span[@id='fenqu_H24R']").click()
filename=time.strftime("%Y%m%d%H%M",time.localtime(time.time()))+'.txt'
#创建文件
output_file=open(filename,'w')
#选择行政区
foriinrange(len(district_navs)):
driver.find_element_by_xpath("//div[@id='"+district_navs[i]+"']").click()
#printdriver.page_source
timeElem=driver.find_element_by_id("time_shikuang")
#输出时间和站点名
output_file.write(timeElem.text+',')
output_file.write(district_names[i]+',')
elems=driver.find_elements_by_xpath("//span[@onmouseover='javscript:changeTextOver(this)']")
#输出每个站点的数据,格式为:站点名,一小时降雨量,当日累积降雨量
foreleminelems:
output_file.write(AMonitorRecord(elem.get_attribute("title"))+',')
output_file.write(' ')
output_file.close()
driver.close()
time.sleep(3600)
[python]view plain
#Encoding=utf-8
defOnlyCharNum(s,oth=''):
s2=s.lower()
fomart=',.'
forcins2:
ifnotcinfomart:
s=s.replace(c,'')
returns
defAMonitorRecord(str):
str=str.split(":")
returnstr[0]+","+OnlyCharNum(str[1])
5. 刚学python,抓中文网页遇到编码的问题,怎么转换也不行
其实你可以用现成的框架,比如scrapy,已经帮你处理了编码的问题。
如果一定要自己写的话,可以先看一下你抓取站点的编码,一边页面里都会有,比如网络知道里的:
<meta http-equiv="content-type" content="text/html;charset=gbk" />
说明是gbk编码。
#str是你获取到的页面内容
str.decode("gbk")
这样生成的就是python内部编码unicode了,如果你再想编码成utf8,可以:
str.encode("utf8")
如果解决了您的问题请采纳!
如果未解决请继续追问!
6. python里面request怎么读取html代码
使用Python 3的requests模块抓取网页源码并保存到文件示例:
import requests
ff = open('testt.txt','w',encoding='utf-8')
with open('test.txt',encoding="utf-8") as f:
for line in f:
ff.write(line)
ff.close()
这是演示读取一个txt文件,每次读取一行,并保存到另一个txt文件中的示例。
因为在命令行中打印每次读取一行的数据,中文会出现编码错误,所以每次读取一行并保存到另一个文件,这样来测试读取是否正常。(注意open的时候制定encoding编码方式)
7. python 用requests获取网页源代码为什么中文显示错误
查看一下网页的编码,比如是gbk的话,就r.encoding='gbk'。一下内容摘自requests文档
requests会自动解码来自服务器的内容。大多数unicode字符集都能被无缝地解码。
请求发出后,requests会基于http头部对响应的编码作出有根据的推测。当你访问
r.text
之时,requests会使用其推测的文本编码。你可以找出requests使用了什么编码,并且能够使用
r.encoding
属性来改变它:
r.encoding
'utf-8'
r.encoding
=
'iso-8859-1'
如果你改变了编码,每当你访问
r.text
,request都将会使用
r.encoding
的新值。你可能希望在使用特殊逻辑计算出文本的编码的情况下来修改编码。比如
http
和
xml
自身可以指定编码。这样的话,你应该使用
r.content
来找到编码,然后设置
r.encoding
为相应的编码。这样就能使用正确的编码解析
r.text
了。
8. python,requests中获取网页源代码,与右键查看的源代码不一致,求解!!! 下面是代码,不知有何错误
requests请求网址url = 'https://www..com/s?wd=周杰伦'后,print(res.text) #打印的只是url = 'https://www..com/s?wd=周杰伦 这一个请求返回的响应体内容,
而如下图,右键查看的页面源代码是你请求的网页url加上其他页面内的js请求,图片等静态资源请求,css等最终形成的页面,所以两者不一样的
9. 求python抓网页的代码
python3.x中使用urllib.request模块来抓取网页代码,通过urllib.request.urlopen函数取网页内容,获取的为数据流,通过read()函数把数字读取出来,再把读取的二进制数据通过decode函数解码(编号可以通过查看网页源代码中<meta http-equiv="content-type" content="text/html;charset=gbk" />得知,如下例中为gbk编码。),这样就得到了网页的源代码。
如下例所示,抓取本页代码:
importurllib.request
html=urllib.request.urlopen('
).read().decode('gbk')#注意抓取后要按网页编码进行解码
print(html)
以下为urllib.request.urlopen函数说明:
urllib.request.urlopen(url,
data=None, [timeout, ]*, cafile=None, capath=None,
cadefault=False, context=None)
Open the URL url, which can be either a string or a Request object.
data must be a bytes object specifying additional data to be sent to
the server, or None
if no such data is needed. data may also be an iterable object and in
that case Content-Length value must be specified in the headers. Currently HTTP
requests are the only ones that use data; the HTTP request will be a
POST instead of a GET when the data parameter is provided.
data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.parse.urlencode() function takes a mapping or
sequence of 2-tuples and returns a string in this format. It should be encoded
to bytes before being used as the data parameter. The charset parameter
in Content-Type
header may be used to specify the encoding. If charset parameter is not sent
with the Content-Type header, the server following the HTTP 1.1 recommendation
may assume that the data is encoded in ISO-8859-1 encoding. It is advisable to
use charset parameter with encoding used in Content-Type header with the Request.
urllib.request mole uses HTTP/1.1 and includes Connection:close header
in its HTTP requests.
The optional timeout parameter specifies a timeout in seconds for
blocking operations like the connection attempt (if not specified, the global
default timeout setting will be used). This actually only works for HTTP, HTTPS
and FTP connections.
If context is specified, it must be a ssl.SSLContext instance describing the various SSL
options. See HTTPSConnection for more details.
The optional cafile and capath parameters specify a set of
trusted CA certificates for HTTPS requests. cafile should point to a
single file containing a bundle of CA certificates, whereas capath
should point to a directory of hashed certificate files. More information can be
found in ssl.SSLContext.load_verify_locations().
The cadefault parameter is ignored.
For http and https urls, this function returns a http.client.HTTPResponse object which has the
following HTTPResponse
Objects methods.
For ftp, file, and data urls and requests explicitly handled by legacy URLopener and FancyURLopener classes, this function returns a
urllib.response.addinfourl object which can work as context manager and has methods such as
geturl() — return the URL of the resource retrieved,
commonly used to determine if a redirect was followed
info() — return the meta-information of the page, such
as headers, in the form of an email.message_from_string() instance (see Quick
Reference to HTTP Headers)
getcode() – return the HTTP status code of the response.
Raises URLError on errors.
Note that None
may be returned if no handler handles the request (though the default installed
global OpenerDirector uses UnknownHandler to ensure this never happens).
In addition, if proxy settings are detected (for example, when a *_proxy environment
variable like http_proxy is set), ProxyHandler is default installed and makes sure the
requests are handled through the proxy.
The legacy urllib.urlopen function from Python 2.6 and earlier has
been discontinued; urllib.request.urlopen() corresponds to the old
urllib2.urlopen.
Proxy handling, which was done by passing a dictionary parameter to urllib.urlopen, can be
obtained by using ProxyHandler objects.
Changed in version 3.2: cafile
and capath were added.
Changed in version 3.2: HTTPS virtual
hosts are now supported if possible (that is, if ssl.HAS_SNI is true).
New in version 3.2: data can be
an iterable object.
Changed in version 3.3: cadefault
was added.
Changed in version 3.4.3: context
was added.
10. 网页编码和Python编码不匹配怎么办
网页编码格式有很多,比如UTF-8,GBK2312等,在网址页面F12键,ctrl+f搜索charset可看到该网页使用的编码格式,如CSDN为charset=”utf-8”。我们使用python获取网页内容时,经常会由于网页编码问题导致程序崩溃报错或获取到一堆二进制内容,软件的兼容性很差。有一个办法,可以通过第三方库chardet获取编码格式,再使用该编码格式解码数据可实现兼容。
1、安装chardet库
chardet是第三方库,需要先安装再使用。简单的办法是启动DOS界面,进入python安装路径下Scripts路径中(其中有pip脚本),运行”pip install chardet”,即可完成安装(可能需要先更新pip,根据提示运行命令即可);
2、导入charset、建立函数
python工程中导入charset库(”import chardet”);建立函数如下:
def get_url_context(url):
content = urllib.request.urlopen(url) #获取网页内容
encode = chardet.detect(content) #获取网页编码格式字典信息,字典encode中键encoding的值为编码格式
return content.decode(encode['encoding'], 'ignore') #根据获取到的编码格式进行解码,并忽略不能识别的编码信息
以上函数的返回值即为网页解码后的内容,无论网页是哪种格式编码,都能轻松识别转换;需要注意的是解码时要加参数’ignore’,否则网页中可能会有混合编码导致程序出错。