美文网首页
极简爬虫教程

极简爬虫教程

作者: 一石匠人 | 来源:发表于2022-04-13 21:44 被阅读0次

    爬虫总体上可以分为步:获取网页、解析网页(也就是找到想要的信息)、保存信息

    一、准备工作

    1.获取网页

    需要用到requests库,最常用得是get()方法

    import requests
    link = 'https://网址xxxxx/'
    response  = requests.get(link)
    

    这样就获取了网页,想要进一步查看网页,需要用到text属性

    print(response.text)`
    

    2、解析网页(也就是找到想要的信息)

    需要用到bs4库

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(response.text,'html.parser')
    

    找到对应标签需要用到find_all方法

    soup = BeautifulSoup(response.text,'html.parser').find_all(name='div',class_="top-ok")
    

    3、保存信息

    with open('book.txt','a+') as f:
            f.write(m.text+'\n')
    

    二、爬虫程序最小框架

    结合上面所说,爬虫最小框架得代码为

    import requests
    from bs4 import BeautifulSoup
    # 获取网页
    link = 'https://网址xxxxx/'
    response  = requests.get(link)
    # 解析网页
    soup = BeautifulSoup(response.text,'html.parser').find_all(name='div',class_="top-ok")
    # 保存信息
    with open('book.txt','a+') as f:
        f.write(m.text+'\n')
    

    三、额外说明

    为了顺利爬取网站信息,有几个必备技能一定要了解。

    1.headers

    为了对付“反爬虫”,我们需要让程序觉得是人在操作,最基本得方法是设置headers

    headers = {'User-Agent': 'xxx此处换为自己的信息xxxx'}
    link = 'https://网址xxxxx/'
    response  = requests.get(link ,headers = headers)
    

    2.编码方式设定

    有时候爬取下来得信息会出现乱码,这时候需要通过设置编码解决。常见得编码方式为UTF-8、GBK

    response  = requests.get(link ,headers = headers)
    response.encoding = 'UTF-8'
    

    所以我们得爬虫最小框架进化成了下面得形式

    import requests
    from bs4 import BeautifulSoup
    # 获取网页
    headers = {'User-Agent': 'xxx此处换为自己的信息xxxx'}
    link = 'https://网址xxxxx/'
    response  = requests.get(link ,headers = headers)
    response.encoding = "UTF-8"
    # 解析网页
    soup = BeautifulSoup(response.text,'html.parser').find_all(name='div',class_="top-ok")
    # 保存信息
    with open('book.txt','a+') as f:
        f.write(m.text+'\n')
    

    四、举例

    举例子。此处需要把headers设置成自己得才能正常运行。

    import requests
    from bs4 import BeautifulSoup
    headers = {'User-Agent': 'xxx此处换为自己的信息xxxx'}
    link = 'https://wap.etgushi.com/'
    response  = requests.get(link ,headers = headers)
    response.encoding = 'UTF-8'
    print(response.text)
    soup = BeautifulSoup(response.text,'html.parser').find_all(name='div',class_="top-ok")
    for n in soup:
       n = n.find_all(name='a')
       for m in n:
           with open('book.txt','a+') as f:
               f.write(m.text+'\n')
    
    

    相关文章

      网友评论

          本文标题:极简爬虫教程

          本文链接:https://www.haomeiwen.com/subject/lbfzsrtx.html