获取网页源代码 python_python 获取网页源代码

import re #正则表达式模块

import urllib.request

import time #时间模块

import string #字符串模块

def getHtml(url):f=urllib.request.urlopen(url)

print(f.read())

if name == '__main__':

getHtml('http://www.baidu.com/')

下面的是获取网页代码不乱码

import re #正则表达式模块

import urllib.request

import time #时间模块

import string #字符串模块

def getHtml(url):f=urllib.request.urlopen(url)

print(str(f.read(),'utf-8'))

if name == '__main__':getHtml('http://www.baidu.com/')

第三种获取网页源代码方法

import requests

req = requests.get("http://news.sina.com.cn/")

if req.encoding == 'ISO-8859-1':encodings = requests.utils.get_encodings_from_content(req.text)

if encodings:

encoding = encodings[0]

else:

encoding = req.apparent_encoding

# encode_content = req.content.decode(encoding, 'replace').encode('utf-8', 'replace')

global encode_content

encode_content = req.content.decode(encoding, 'replace') #如果设置为replace,则会用?取代非法字符;

print(encode_content)

with open('test.html','w',encoding='utf-8') as f:f.write(encode_content)

alipayimg.png支付宝打赏

weipayimg.png微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值