参考慕课 python网络爬虫与信息提取 视频和课件
总览
1.Requests自动爬取HTML页面,自动网络提交
(robots.txt网络爬虫)
2.BeautifulSoup解析HTML界面
(正则表达式、提取页面关键信息)
3.*Scrapy网络爬虫原理,专业爬虫框架介绍
网络爬虫尺寸
第一章Request库入门
安装 pip install requests
(升级pip pip install --upgrade pip
)
r = requests.get(url)
r:response 返回一个包含服务器
资源的Response对象
request:返回一个包含服务器
资源的Response对象
r.encoding:如果header中不存在charset,默认ISO-8859-1
异常exception
requests异常
response异常
通用代码框架
import requests
def getHTMLText(url):
try:
r = requests.get(url,timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "产生异常"
if __name__ == "__main__":
url = "http://www.baidu.com"
print(getHTMLText(url))
HTTP是一个基于“请求与响应”模式的、无状态的应用层协议,采用URL作为定位网络资源的标识, URL格式如下:
http://host[:port][path]
URL是通过HTTP协议存取资源的Internet路径
HTTP协议对资源的操作
head()
r = requests.head(url)
r.headers
post()
put()
…
requests.request(method, url, **kwargs)
**kwargs: 控制访问的参数,均为可选项
params : 字典或字节序列,作为参数增加到url中
data : 字典、字节序列或文件对象,作为Request的内容
第二章 安全、隐私、限制问题
判断user-agent
只响应浏览器或友好怕从
发布公告:robots协议
第三章 BeautifulSoup入门
解析、遍历、维护“标签树”的功能库
安装:pip install beautifulsoup4
import requests
r = requests.get("https://www.")
demo = r.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(demo,'html.parser')
print(soup.prettify())
返回html
类基本元素
tag:任何存在于HTML语法中的标签都可以用soup.访问获得;当HTML文档中存在多个相同对应内容时, soup.返回第一个
.name
.attrs
.string
…
3.1基于bs4库的HTML内容遍历方法
标签树木下行遍历
for child in soup.body.children:
print(child)
上行遍历
平行遍历
平行遍历发生在同一个父节点下的各节点间
3.2基于bs4库的HTML格式输出
prettify()
为HTML文本<>及其内容增加更加’\n’
方法: .prettify()
bs4库将任何HTML输入都变成utf‐8编码
第四章 信息标记与提取方法
第五章 正则表达式入门
可参考:python正则表达式入门
第六章 Scrapy爬虫框架
第七章 Scrapy爬虫基本使用
Requests库网络爬取实战
import requests
def getHTMLText(url):
try:
r = requests.get(url,timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text[:1000]
except:
return "爬虫失败"
if __name__ == "__main__":
url = "http://www.baidu.com"
print(getHTMLText(url))
getHTMLText("https://**")
Scrapy实战一
爬取股票信息
文件目录
关键代码stocks.py
# -*- coding: utf-8 -*-
import scrapy
import re
class StocksSpider(scrapy.Spider):
name = "stocks"
start_urls = ['http://quote.eastmoney.com/stocklist.html']
def parse(self, response):
for href in response.css('a::attr(href)').extract():
try:
stock = re.findall(r"[s][hz]\d{6}", href)[0]
url = 'https://gupiao.baidu.com/stock/' + stock + '.html'
yield scrapy.Request(url, callback=self.parse_stock)
except:
continue
def parse_stock(self, response):
infoDict = {}
stockInfo = response.css('.stock-bets')
name = stockInfo.css('.bets-name').extract()[0]
keyList = stockInfo.css('dt').extract()
valueList = stockInfo.css('dd').extract()
for i in range(len(keyList)):
key = re.findall(r'>.*</dt>', keyList[i])[0][1:-5]
try:
val = re.findall(r'\d+\.?.*</dd>', valueList[i])[0][0:-5]
except:
val = '--'
infoDict[key]=val
infoDict.update(
{'股票名称': re.findall('\s.*\(',name)[0].split()[0] + \
re.findall('\>.*\<', name)[0][1:-1]})
yield infoDict