python 学习 初入爬虫

1.爬取网页内容

import urllib.request as ur
import chardet as ct
response=ur.urlopen("http://www.fishc.com")
html=response.read()
result=ct.detect(html)['encoding']
html=html.decode(result)
print(html)

知识点:
urlib.request模块,可以用来请求访问网址
chadet模块可以用来,检测编码方式
ur.urlopen()函数,获得 HTTPRespone类型,用read()函数读取内容
chadet,detect()函数,获得 编码方式和可信度
decoed(‘解码方式’)解码

2.写一个程序,依次访问文件中指定的站点,并将每个站点返回的内容依次存放到不同的文件中。
urls.txt文件中的站点

http://www.fishc.com
http://www.baidu.com
http://www.zhihu.com
http://www.taobao.com

test.py文件,用于读取 网站内容 和编码方式

import urllib.request as ur
import chardet as ct
def getresult(http):
    response=ur.urlopen(http)
    html=response.read()
    result=ct.detect(html)['encoding']
    html=html.decode(result)
    return (html,result)

主文件中,将内容放在,相应文件中

import test as t

def geturl():
    with open(r"E:\urls\urls.txt",'r') as f:
        for each in f:
            each=each.strip('\n')
            url,encode=t.getresult(each)
            each='.'.join(['E:\\urls\\',each.split('.',2)[1],'txt'])
            with open(each,'w',encoding=encode) as filewrite:
                filewrite.write(url)
geturl()

ps:本来还有 豆瓣网站 http://www.douban.com 但是无法爬取,会报错,不知道什么原因。
知识点:
with语句 可以控制关闭文件
.join([ ])函数,字符合并函数
strip() 函数,去除函数
元组返回参数,可以返回多个值

猜你喜欢

转载自blog.csdn.net/m0_52521883/article/details/113820821