python简单爬虫,爬取整个页面

简单的爬虫,爬取整个页面,修改代码中的url可爬取指定网站。

import urllib.request  # 导入包


def getHtml(url):  # 获取html的内容
    html = urllib.request.urlopen(url).read()  # bytes 如果不用read()html会是一个↓
    return html                                # http.client.HTTPResponse的变量


def saveHtml(fileName, fileContent):
    with open(fileName, "wb") as f:  # 以wb打开文件
        f.write(fileContent)  # 写入


def main():
    url = "https://www.zhihuishu.com/"  # url
    html = getHtml(url)  # 调用函数获取bytes
    saveHtml("theHtml.html", html)  # 保存
    print("保存网页完成")  # 提示语


if __name__ == "__main__":  # 主函数
    main()

遗留问题:有不少网站有反爬虫机制,导致爬到的文件并非是想要的文件。

猜你喜欢

转载自blog.csdn.net/weixin_51343683/article/details/109295084
今日推荐