Python爬虫的基本思路

人生苦短,我用Python;本文章主要整理一下Python爬虫程序基本逻辑思路。

Python爬虫的基本思路

人生苦短,我用Python;本文章主要整理一下Python爬虫程序基本逻辑思路。以一个简单的爬虫程序为例

1、确定目标网站

https://bh.sb/post/category/main/</code></pre>

2、分析被爬去网站数据来源结构,即分析数据请求url格式

url = 'https://bh.sb/post/category/main/page/2/'</code></pre>

3、编写程序代码

3.1、程序入口代码

if __name__ == "__main__":
    main()</code></pre>

3.2、模拟浏览器请求数据

利用requests模拟浏览器

def get_html(url):
    #添加headers头
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0'
    }
    response = requests.get(url, headers=headers);
    response.encoding = 'utf-8'
    if response.status_code == 200:
        return response.text
    return None</code></pre>

其中添加headers用来模拟火狐浏览器,参数User-Agent也可以是谷歌浏览器或者其他浏览器

3.3、分析数据,通过解析方式,得到有用的数据

#2、解析内容
def parse_html(html, csv):
    soup = BeautifulSoup(html, 'lxml')
    data = soup.find_all('article')
    
    for item in data:
        #print(item.a.text)
        title = item.a.get_text()
        author = item.select('.text-muted.time')[0].get_text().split(' ')[0]
        img_href = item.select('img')[0].attrs['src']
        note = item.select('.note')[0].get_text()

        li = [title, author,  note, img_href]</code></pre>

解析数据使用bs4,xPath等,这里使用bs4

从数据中解析出title,author,img_href,note等信息,存在列表li中

3.4、保存数据

可以保存为文件或者保存到数据库中,该例子中保存到csv中

#3、保存数据
def init_csv():
    #歌单csv文件
    csv_file = open('1.csv', 'w', newline='', encoding='utf-8-sig')
    writer = csv.writer(csv_file)
    writer.writerow(['标题', '作者',  '简介', '图片链接'])
    return writer</code></pre>

最后一步进行数据分析以及可视化等。本文不做介绍

上一篇:整理Yii2中定义的常用路径别名 下一篇:多线程爬去英雄联盟所有英雄的皮肤

评论

评论(0)

暂无评论