Page format problems urllib.request.urlopen.read read in Python3

Source: Internet
Author: User

#!/usr/bin/ Env Python3
#-*-coding:utf-8-*-#<a title=""target="_blank"href="http://blog.sina.com.cn/s/blog_4701280b0102eo83.html"> on the seven elements of the film--About my electric ...</a>Import URLLIB.REQUESTSTR0=r'<a title= "" target= "_blank" href= "http://blog.sina.com.cn/s/blog_4701280b0102eo83.html" > "Seven elements of film"-- About me on the electric ...</a>'Title0=str0.find (R'<a title') print (TITLE0) href0=str0.find (R'href') print (HREF0) html0=str0.find (R'HTML') print (html0) URL=str0[href0+6: html0+4]print (URL) content= Urllib.request.urlopen (URL). Read () #当该语句读取的返回值是bytes类型时 to convert it to utf-8 to normally display the print (type content) #此时为bytes类型print in a Python program (Content.decode ('Utf-8')) #需要进行类型转换才能正常显示在python中print (Type (Content.decode ('Utf-8')) #返回解码后的类型, this is the str type filename= url[- -:]open (filename,'WB'). Write (content) #在写文件时 to be written as a bytes type of file ' WB '

Beginner python, used python3.5, according to the tutorial to write code, the crawl of the page is a Sina blog article, in the use of Urllib.request.urlopen (URL). Read () When the return value is found The type of content is bytes, which is garbled when Python is printed without a type conversion.

The solution is to decode the content into a utf-8 type and print it out as a file with a ' WB ' written as a byte file.

The type of the head position display is utf-8 when the Review element page opens in Google Chrome, but the actual Python program reads the format bytes type, which is puzzling.

Page format problems urllib.request.urlopen.read read in Python3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.