Python爬虫系统学习(1)

Python爬虫系统化学习(1)

前言:爬虫的学习对生活中很多事情都很有帮助,比如买房的时候爬取房价,爬取影评之类的,学习爬虫也是在提升对Python的掌握,所以我准备用2-3周的晚上时间,提升自己对Python爬虫的掌握。

Python爬取目标的三个流程:

1.获取页面:

基础技术:request,urllib,selenium

进阶技术:多线程多进程抓取,登陆抓取,突破IP封禁,使用服务器抓取

2.解析页面:

基础技术:re正则表达式,BeatuifulSoup和lxml

进阶技术:解决中文乱码方法

3.存储页面:

基础技术:存入txt文件和存入csv文件

进阶技术:存入MySQL数据库和MongDB数据库


首先根据书籍,我写了如下的代码:

#!/usr/bin/python
# coding=utf-8
from bs4 import BeautifulSoup
import requests
link ="http://www.santostang.com/"
r=requests.get(link)
soup=BeautifulSoup(r.text,"html.parser")
title=soup.find("h1",class_="post-title").a.text.strip()
with open('title_text.txt',"a+") as f:
f.write(title)

代码目的为:获取URL的前端源码中h1标签中以post-title为class的a标签的文本,并且去除两端的空格,比如获取到:

<h1 class="post-title"><a> 这是被爬取的内容</a></h1>

实现过程报错:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

经过查询,报错原因是Unicode编码与ASCII编码的不兼容,Python脚本文件是由utf-8编码的。,在源代码头部添加修改编码格式的代码

import sys
reload(sys)
sys.setdefaultencoding('u')

爬取成功

实验二:访问B站50个网页,测试访问状态

#!/usr/bin/python
#coding:utf-8
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from bs4 import BeautifulSoup
head={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0","Host":"www.bilibili.com"}
link="https://www.bilibili.com/v/technology/career/spm_id_from=333.5.b_7375626e6176.6#/all/default/0/"
def GetName(url,i):
url=url+str(i)+'/'
tr=requests.get(url,headers=head)
print(url,':',str(tr.status_code))
for i in range(51):
GetName(link,i)

反思不足:其实已经可以爬取得到网页源码了,但是不会解析,正则匹配的数量过多导致失败,导致只能进行到这一步。

收获:

①:print('haha', end=""),不换行打印

②:sys 重新修改python编码

③:heads字典加载放到requests请求里

④:URL加载与组合

⑤:追写文件的方法,前单引号,后双引号:

with open(‘a.txt’,"a+") as f:
f.write(text)
上一篇:操作系统内核Hack:(三)引导程序制作


下一篇:Python爬虫的学习经历