zoukankan      html  css  js  c++  java
  • 我的第一个py爬虫-小白(beatifulsoup)

    一、基本上所有的python第一步都是安装、安装

    我用到的第三方安装包(beatifulsoup4、re、requests)、还要安装lxml

    二、找个http开头的网址我找的是url="http://www.bestgushi.com/"一个看故事的网站

    三、分析网站的源码

        

    故事基本上都在a标签的链接里

    四、开始写爬虫代码

    1.把库导入进去

    from  bs4 import BeautifulSoup

    import requests

    import re

    2.用requests请求把源码获取到并解析

    # url="http://www.bestgushi.com/"
    file=requests.get(url).text#获取源码
    new_lile=BeautifulSoup(file,'lxml')#解析源码

    3.使用beatifulsoup内的find_all函数找到所有的a标签

      先定义一个实例:

    soup=BeautifulSoup(features="lxml")

      再引用函数:
    p_1=new_lile.find_all('a')

    4.因为p_1是个列表利用for循环把所有a标签取出来

    for i in  p_1:
    try:
    result_list=re.findall("'href="'.+'"target'",i)#这个没有必要想看看正则用法但是老是用错所以写个
    except:
    print i['href']

    五、最后附上完整的代码:

    # -*- coding: utf-8 -*-
    from bs4 import BeautifulSoup
    import requests
    import re
    #"url=view-source:http://www.bestgushi.com/"
    class pachong:
    def pa_a(self,url):
    # url="http://www.bestgushi.com/"
    file=requests.get(url).text
    new_lile=BeautifulSoup(file,'lxml')
    # print (new_lile)
    soup=BeautifulSoup(features="lxml")
    p_1=new_lile.find_all('a')

    for i in p_1:
    try:
    result_list=re.findall("'href="'.+'"target'",i)
    except:
    print i['href']
    x=pachong()
    x.pa_a("http://www.bestgushi.com/")
  • 相关阅读:
    JAVA周二学习总结
    2019春总结作业
    第十二周作业
    第十一周作业
    第十周作业
    第九周作业
    第八周作业
    第七周作业
    第六周作业
    第四周课程总结&试验报告(二)
  • 原文地址:https://www.cnblogs.com/xifengqidama/p/9707172.html
Copyright © 2011-2022 走看看