首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python爬虫入门

网络爬虫,即通过程序的方式获取互联网或其它内网的内容数据,有结构化的数据也有非结构化数据。

Python在该领域非常受欢迎,对于很多科研人员、程序员来说,获取结构化数据是进行数据分析的必要前提。

下面我们来学习下怎么使用Python进行获取网页内容。注意,以下内容只适合获取非渲染方式的网页,若要使用高级方式则需要引入selenium等其它工具。selenium将在以后的文章中学习。

Python 安装

python 版本分两个主线2.x 和3.x,相互之间不兼容。3.x版本不往下兼容,所以最好是选择3.x版本。

在linux centos下安装

1.先安装依赖

yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel

2.下载源码

https://www.python.org/ftp/python/3.8.2/Python-3.8.2.tgz

3.创建目录并解压:

mkdir -p /usr/local/python3

tar -zxvf Python-3.8.2.tgz

4.编译

cd Python-3.8.2

./configure --prefix=/usr/local/python3

make

make install

5.建立软链

ln -s /usr/local/python3/bin/python3 /usr/bin/python3

6.修改Path

PATH``=``$PATH:$HOME``/``bin``:``/``usr``/``local``/``python3``/``bin

export PATH安装PiP

1.获取安装文件

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

2.执行

python get-pip.py

3.使用pip安装依赖

pip install requests

pip install lxml编写爬虫

我们以豆瓣为例,获取热门内容作为学习内容,直接上代码:

# -*- coding:utf-8 -*-

import os

import re

import sys

import time

import json

import datetime

import requests

from lxml import etree

def parse_douban():

try:

url = "https://www.douban.com/group/explore"

headers={

"User-Agent" : "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.6) ",

"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",

"Accept-Language" : "en-us",

"Connection" : "keep-alive",

"Accept-Charset" : "GB2312,utf-8;q=0.7,*;q=0.7",

"Host": 'www.douban.com',

"Referer": 'https://www.douban.com/group/explore'

}

fname = "douban.json"

r = requests.get(url, headers=headers, timeout=(5, 10))

soup = etree.HTML(r.text)

list = []

jsondict= {}

list_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

jsondict["time"] = list_time

jsondict["title"] = "豆瓣讨论精选"

for soup_a in soup.xpath("//div[@class='channel-item']/div[@class='bd']/h3/a"):

blist = {}

hot_name = soup_a.text.replace("\\n", "").replace("\n", "").replace("\\r", "").replace("\r", "").strip()

hot_url = soup_a.get('href')

group = "douban"

blist["name"]=hot_name

blist["url"]=hot_url

list.append(blist)

jsondict["data"]=list

print(json.dumps(jsondict, ensure_ascii=False, indent=2, separators=(',',':')))

except:

print(sys._getframe().f_code.co_name+"采集错误,请及时更新规则!")

if __name__ == "__main__":

parse_douban()

在这个代码里面使用到requests获取网页内容,lxml作为解析网页内容并保存到json串。

headers 是HTTP协议里面的一部分,是服务器识别客户端环境的参数,也有服务器作为反爬虫的识别。

headers={

"User-Agent" : "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.6) ",

"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8",

"Accept-Language" : "en-us",

"Connection" : "keep-alive",

"Accept-Charset" : "GB2312,utf-8;q=0.7,*;q=0.7",

"Host": 'www.douban.com',

"Referer": 'https://www.douban.com/group/explore'

}

这里是伪装成浏览器发起访问。

r = requests.get(url, headers=headers, timeout=(5, 10));

这行是使用requests获取网页内容,使用相对其它Http库简单易用得多。非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症、冗余代码症、重新发明轮子症、啃文档症、抑郁、头疼。

Requests 是以PEP 20的箴言为中心开发的

Beautiful is better than ugly.(美丽优于丑陋)

Explicit is better than implicit.(直白优于含蓄)

Simple is better than complex.(简单优于复杂)

Complex is better than complicated.(复杂优于繁琐)

Readability counts.(可读性很重要)

对于 Requests 所有的贡献都应牢记这些重要的准则。

获取到内容后即使用etree 解析,使用xpath方式获取我们需要的属性或者text。

soup.xpath("//div[@class='channel-item']/div[@class='bd']/h3/a")

这行是获取以下结构中 超链接a 的Element,再通过soup_a.get('href')即可获取url内容。

根据网页内容定制json,这里不再展开。

将代码保存在 caiji.py执行即可。

python3 caiji.py

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20200430A0GG9Y00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券