python3爬虫第一步-爬取网页源码

python3爬虫第一步-爬取网页源码

典型的源码百度一下就有了
import urllib.request
def getHtml(url):
page=urllib.request.urlopen(url)
html=page.read()
return html
html=getHtml(“https://www.cxy61.com/cxyteam/cxyteam_forum/add.html?pk=2#“)
print(html)
打印结果如下:
python3爬虫第一步-爬取网页源码
结果正确进一步存储爬虫结果
import urllib.request
f=open(“./title.html”,”w”)
def getHtml(url):
page=urllib.request.urlopen(url)
html=page.read()
return html
html=getHtml(“https://www.cxy61.com/cxyteam/cxyteam_forum/add.html?pk=2#“)
print(html)
f.write(html)
然后就报错了:
python3爬虫第一步-爬取网页源码
折腾好久,终于找到原因,文件打开方式有问题,把之前的打开语句修改为用二进制方式打开就没有问题
import urllib.request
f=open(“./title.html”,”wb+”)
def getHtml(url):
page=urllib.request.urlopen(url)
html=page.read()
return html
html=getHtml(“https://www.cxy61.com/cxyteam/cxyteam_forum/add.html?pk=2#“)
print(html)
f.write(html)
结果就正确了!
记录下来共勉。