import requests from lxml import etree # 格式化网页代码需要用到 res = requests.get("https://www.baidu.com") ####此处可以提前指定访问编码,否则后边不确定编码格式 ####方便输出 网页用的其他格式也会转换过来 比较方便 res.encoding = "utf-8" #### 返回状态 print(res.status_code) print(res.encoding) ####res已经是返回的object #print(res.text) print(type(res)) #res <class 'requests.models.Response'> print("***********************************************") #### bytes型数据 可以直接流式往文本文件里写 中文字符都转换为 \xe5\x85\xb3\xe4 html_txt = res.content #print(html_txt) print(type(html_txt)) # <class 'bytes'> print("***********************************************") #### 转换后成了str类型,改变编码 html_doc = str(html_txt,"utf-8") #print(html_doc) print(type(html_doc)) # res <class 'str'> print("***********************************************") #### wd 读写方式只能写 bytes 类型的数据 html_txt with open("test_txt.html","wb") as f: f.write(html_txt) ##### 转换成 str类型之候 写入文件的时候不能用 WB 了 只能用 w 因为指定了编码为 UTF-8 此时需要转换编码 with open("test_doc.html","w",encoding="utf-8") as f: f.write(html_doc) ####开始过滤代码 html = res.text #### 构造XPath解析对象,同时可以自动修正HMTL文本(标签缺少闭合自动添加上) #### 对象不能直接输出 也不能写入记事本 select_txt = etree.HTML(html) #<Element html at 0x234c140> title = select_txt.xpath("//title/text()") print(title) print(title[0])